Martian
Martian

Reputation: 11

How do I get the specific gameobject clicked on out of many using that script in Unit2d C#?

I have a bunch of gameobjects with the following script attached. I am trying to get the specific gameobject clicked on so I can move it. The debug fundtion works fine, but I can't access the object to move it.

public void OnMouseDown()
{
    Debug.Log(senatorName + " is in chamber " + inChamber);
    GameObject disSenator = GameObject.Find(senatorName);
    newPos = new Vector3(0, 0, -2);
    disSenator.MoveSenator(newPos);
}

public void MoveSenator(Vector3 newPos)
{
    senator.transform.position = newPos;
}

The script objects to the line disSenator.MoveSenator(newPos);

I've tried a bunch of other methods and nothing works even when I get no errors.

Thanks in advance for answering a newbie question.

Upvotes: 0

Views: 68

Answers (3)

Martian
Martian

Reputation: 11

HORRAY!!! I stumbled onto the solution while flailing in vain. The trick is to get the Rigidbody rather than the GameObject. Here's the code that works:

 public void OnMouseDown()
    {
        Debug.Log(senatorName + " is in chamber " + inChamber);
        rbSenator = GetComponent<Rigidbody2D>();
        string newChamber = chooseMove(inChamber);
        newPos = actMove(newChamber);
        inChamber = newChamber;
        rbSenator.transform.position = newPos;
        Debug.Log(senatorName + " is in chamber " + inChamber);
    }

Upvotes: 0

Shay Yizhak
Shay Yizhak

Reputation: 91

Assuming you inherit from MonoBehavior, this should work, for each object the mouse is clicking on, that has this script:

public void OnMouseDown()
{
    Debug.Log(senatorName + " is in chamber " + inChamber);
    newPos = new Vector3(0, 0, -2);
    transform.position = newPos;            
}

Upvotes: 2

xander
xander

Reputation: 1709

Use MonoBehavior's gameObject property to access the object that the script is attached to: https://docs.unity3d.com/ScriptReference/Component-gameObject.html

Upvotes: 0

Related Questions