-1
\$\begingroup\$

Earlier I had a script attached to my player for its movement using keyboard inputs. Then I decided to do the same thing using onscreen UI buttons so I created an empty gameobject inside my canvas and added the buttons to it and also attached a new script to it which would change the position of my player on pressing those buttons. But my buttons don't work for obvious reasons since I am not actually changing my player's position yet. If I were on the same gameobject like before I would simply do:

transform.position = <new position here>;

Can anyone tell me how to do this exact thing on another gameobject's script?

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Exactly the same, but you should access Transform of object you want to affect. It can be done by searching, or collision detection, or assigning to editor variable, or several more ways (depends on what you want to achieve). \$\endgroup\$ – lentinant Sep 9 '16 at 7:49
5
\$\begingroup\$
//This script will explain how to reference a gameObject 
using UnityEngine;

public class HowToReference : MonoBehaviour {

    //We start of by decalring a class variable of the type GameObject. This can be public if we  want to asing it from the editor.
    public GameObject myFirstObjectReference;
    // Use this for initialization
    void Start () {
        //Now we will explroe severel ways of how to asing our object from code.
        myFirstObjectReference = GameObject.Find("Name of the object in the scene");//This will search for the object by name;
        myFirstObjectReference = GameObject.FindGameObjectWithTag("The tag of the game object");//This will find a gameObject with the specified tag
        //By making the field public in the declaration we could also simply use drag and drop to asing the reference from the unity editor. There are plenty of tutorials online for this.
    }

    // Update is called once per frame
    void Update () {
        // Now that we have a reference we can do what ever we want with the object. For example :
        myFirstObjectReference.transform.position = new Vector3(1, 1, 1);
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.