- Home /
How do you reference a GameObject in a C# script that is a part of that GameObject?
I am instantiating a prefab GameObject that possesses a C# script. Within this script I need to reference the same GameObject that possesses this script. How do I do this? I will have to do this for multiple instantiations of the GameObjects. Not that it's particularly relevant, but I am wanting to reference the GameObject so that I can change the layer value. Much thanks in advance to any help given.
Well, I'm not sure what you are asking. If a script is attached to GameObject someObject, then you can access this object by simply using gameObject. gameObject.layer = ....; If you want to define object from another object's script, then it would be: GameObject someObject; someObject = Instantiate ..... as GameObject; someObject.layer = ....;
Does that help?
Well, yes. robertbu said more or less the same in his answer below. Problem solved.
Answer by robertbu · Mar 18, 2014 at 09:40 PM
From any script, on that game object, you can use 'gameObject' (with a small 'g') to reference the game object itself. So you can do:
gameObject.name = "NewName";
gameObject.layer = 2;
Note that often you will end up with other components of other game objects. Like it's collider or its transform.
other.gameObject.name = "foo";