- Home /
[Simple] C# Retrieving the game object that the script is called.
Greetings,
I've been using C# only and I'm wondering if we can retrieve the game object that the script is called.
What I mean by that is that in my program I've "assigned" (if that's what it is called) the same script to multiple different game objects in my program and in the code I want to retrieve which object is currently executing the code (every object will execute the same code in their own ways when the time comes).
I've solved the problem by doing something like this:
// This object is a prefab (using default values from assets)
public Transform objectO;
// I drag and drop the following from the IDE
public Transform currentGameField;
// I do that to every object that the script is assigned.
void OnMouseDown(){
//Scaling
objectO.localScale = new Vector3(3.5f, 3.5f, 3.5f);
// Some more stuff here, skipped
translateObjectO();
}
void translateObjectO(){
Vector3 tempPosition = currentGameField.localPosition;
switch(regionNumber) {
case 1:
tempPosition.y = objectO.localPosition.y + 0.09f;
break;
// Deleted the fallowing code, unecessary here
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
}
// Finally assign back to the object
objectO.localPosition = tempPosition;
}
The problem is that I don't want to drag the game object to currentGameField hundred times. I want to access the object something like:
`this.Transform.localPosition`
where both I don't store the object and don't assign it from IDE. So I want to remove the `currentGameField` in the above code.
Thanks in advance,
Metan
Answer by whydoidoit · Oct 01, 2012 at 10:30 AM
The transform variable contains the transform of the object that the script is attached to, gameObject contains the GameObject. See the inherited variables here for details of all the other things.
It is however worth caching transform in Awake or Start as this yields faster code.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
gameObject are not referenced 2 Answers
Ordering a list of GameObjects 3 Answers