- Home /
How do I access the object the script is attached to?
This one has to be simple, but I can't find the words to Google this.
I have a script attached to an object in Unity. From that script, how do I access the object's name or other properties? I've read this page, but it doesn't seem to address my question.
I've tried Gameobject.name and this.name, but I can't make them work.
Use 'gameObject'...'gameObject.name'...'gameObject.tag'. See the reference page for GameObject for all the properties you can access.
Hmm. This is my code:
if(gameObject.name="RightFeeler"){ Debug.Log ("Right feeler collided"); }
And this is the error: Cannot implicitly convert type 'string' to 'bool'
I don't know what that means. Any ideas?
Comparison is '==', so it should be:
if (gameObject.name == "RightFeeler") {
Debug.Log("Right feeler collided");
}
Incorrect operator in your conditional
== , not = (is equal to, not equals)
if ( gameObject.name == "RightFeeler" )
what do people have against using spaces, there is no optimization in not using spaces, and makes code so much easier to read
Answer by unibotai · Jun 21, 2013 at 06:19 AM
You attatch the script to the object then use the inspector tab in unity. You can also edit the name of the object in inspector.
Answer by Dubious-Drewski · Jun 21, 2013 at 06:27 AM
Oh my God, I needed a '==' instead of a single '='. What a rookie mistake. Thank you, everyone. You're always so helpful.
Answer by bubzy · Jun 21, 2013 at 06:31 AM
according to your code here, you are accessing the name of the gameObject that you attach this script to, not to another gameObject
this wouldn't really work in a collision situation as you want to find out what your current gameObject collided with, it cannot collide with itself.
you may want to look up triggers too http://docs.unity3d.com/Documentation/ScriptReference/Collider.OnTriggerEnter.html
ive found this a good method for finding WHAT you have collided with.
void OnTriggerEnter(Collider other) {
if(other.gameObject.name == "RightFeeler")
{
Debug.Log("Right Feeler collided");
Destroy(other.gameObject); //or whatever
}
}
bubzy: I have a reason for this strange setup.
I am making an insect. I have a body and two child objects acting as a left feeler and a right feeler. The feelers are not physical objects - they simply guide the body away from obstacles when they 'feel' (collide with) something.
So each feeler has a variable for if Collided (true/false), and the body (somehow) pays attention to this and responds to the input.
I don't yet know how to code this, but this is why I'm practicing.