[Simple] C# Retrieving the game object that the script is called.


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(){
   objectO.localScale = new Vector3(3.5f, 3.5f, 3.5f);
   // Some more stuff here, skipped

void translateObjectO(){
   Vector3 tempPosition = currentGameField.localPosition;
   switch(regionNumber) {
   case 1:
      tempPosition.y = objectO.localPosition.y + 0.09f;
   // Deleted the fallowing code, unecessary here
   case 2:
   case 3:
   case 4:
   case 5:
   case 6:
   // 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:


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,


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.