• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
2
Question by Existingman · Dec 31, 2013 at 02:39 AM · this

Does unity alter the C# definition of "this"?

I am trying to create a game by creating objects of custom classes that then instantiate and control prefabs. (I suppose the intended way to use unity is to instantiate prefabs that have controlling scripts attached as components.)

I noticed that the keyword "this" returns the GameObject that the class script is a component of. This means that when I create an object using: "Customer object1 = new Customer();" the "this" keyword returns "null" when it is used inside the "Customer" class definition.

Under normal circumstances, wouldn't the C# "this" method return the instance ID of "object1"??? Is unity changing the definition of "this" to refer to the containing GameObject? I am trying to pass the instance of the object so that other objects can directly refer to it and its properties and methods. Is there some other way to do it?

I tried researching this myself and I found similar posts, but all the answer were along the lines of : "No. You are wrong. 'this' by definition can never return 'null'. You made a mistake in your code when logged the return of 'this'." However, this explanation fails to account for my many null reference exceptions...

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by KellyThomas · Dec 31, 2013 at 02:46 AM

this has the usual c# behavior when using unity.

If it appears to refer to a GameObject it is because most scripts inherent from `MonoBehaviour` and have all of the convenience methods/variables defined there.

Please post the code that is acting strangely and I'm sure we can explain it.

Comment
Add comment · Show 7 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Existingman · Dec 31, 2013 at 06:00 AM 0
Share

Condensing it down to the basic problem, I have the script for my Tower class applied to an empty GameObject called "contains crap". This was just to get it into the game so that I can test its behaviour.

 using UnityEngine;
 using System.Collections;   
 
 public class Tower : Segment {
     
     void Start () {
     
         battlements = new Battlements(this);
         battlements.initialise();
     
     }
     
 }

And then the battlements class contains:

 using UnityEngine;
 using System.Collections;
 
 
 public class Battlements : Component {
     public Segment owner;
     private $$anonymous$$achinolation machinolation;
 
 
     //constructor
     public Battlements(Segment dad)
     {
         owner = dad;
 
     }
 
     // -------------------------------Initialise function
     public void initialise()
     {
         Debug.Log (owner);
 // log says "Contains Crap (Tower)"
         Debug.Log (this);
 //log says "null"
 
 machinolation = new $$anonymous$$achinolation (this);
         machinolation.initialise ();
 
     }
 }

Note that "this" seemers to return "null". The real problem ofcourse, is that any reference to the passed component in the machinolations class results in a null reference exception.

avatar image KellyThomas · Dec 31, 2013 at 06:25 AM 0
Share

Please try adding a "`Debug.Log(battlements);`" line at the end of Tower.Start().

I think that what we are finding is that unity is detecting that this instance of Battlements is an invalid Component ("A component is always attached to a game object.") and casting it to null during a type cast.

avatar image Existingman · Dec 31, 2013 at 07:43 AM 0
Share

That line causes as error:

Assets/scripts/Components/Battlements.cs(29,27): error CS0119: Expression denotes a type', where a variable', value' or method group' was expected

Is the problem that Component is a reserved word? I defined my own class "Component" as the base class for the Battlements class:

 using UnityEngine;
 using System.Collections;
 
 public class Component : Object {
 
     public Segment owner;
 // desclares some other variables
     
     public void initialiseGenerics()
     {
 
         // does some stuff
 
     }
 
     public virtual void initialise(){ }
 
     
 
     public void bump(Tweak tweaked) {
         //do stuff
     }
 }
 
     
avatar image KellyThomas · Dec 31, 2013 at 08:40 AM 0
Share

I think you must have misunderstood what I was saying but is doesn't matter, I was discussing your Battlements being a descendant of Component but the issue can be explored in simpler terms.

If you run the this class against the following alternative "test" classes you will see different results:

Run$$anonymous$$e

 using UnityEngine;
 using System.Collections;
 
 public class Run$$anonymous$$e : $$anonymous$$onoBehaviour {
     void Start () {
          Test test = new Test();
         Debug.Log("test equals null: " + (test == null));
         Debug.Log("test ToString: " + test);
     }
 }

Test #1

 using UnityEngine;
 using System.Collections;

 // inherits from System.Object    
 public class Test {  
 }
 //Output:
 //test equals null: False
 //test ToString: Test

Test #2

 using UnityEngine;
 using System.Collections;

 // inherits from UnityEngine.Object
 public class Test: Object { 
 }
 //Output:
 //test equals null: True
 //test ToString: null

Test #3

 using UnityEngine;
 using System.Collections;

 // inherits from UnityEngine.Object
 public class Test: Object {  
     override public string ToString() {
         return "I'm real";
     }
 }
 //Output:
 //test equals null: True
 //test ToString: I'm real

So as your Battlements class above is a descendant of Unity's Object it was likely being cast to null as part of the Debug.Log(). What I would like to know now is what is required to pass the "`== null`" test?

avatar image Existingman · Dec 31, 2013 at 09:46 AM 0
Share

So in the machicolation object, here is the first place it has a runtime null reference exception:

"if (owner.owner.maxFloor > 0){"

There would of course be a dozen other null reference exceptions past this point. And the Battlements object has no problem referring to this property as: "owner.maxFloor"

Show more comments
avatar image
0

Answer by Existingman · Dec 31, 2013 at 10:01 AM

So in the machicolation object, here is the first place it has a runtime null reference exception:

"if (owner.owner.maxFloor > 0){"

There would of course be a dozen other null reference exceptions past this point. And the Battlements object has no problem referring to this property as: "owner.maxFloor"

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

19 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How to check if object is "this" object? 1 Answer

Cannot reach a planes meshrenderer 0 Answers

How can I get my own gameobject? 2 Answers

How to pass an instance of a custom class into an event within itself? 2 Answers

Hi, getting error cs1041 in my code:identifier expected, "this" is a keyword; need solution please 3 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges