Saturday, February 16, 2019

unity - How do you reference one game object from another?


I am trying to reference a game object that was created in the editor and added to the scene (not created dynamically). How can I reference this object in a script added to another gameobject?


For example I have a Mesh called QuantumCold_B (in the editor), and I try to get its position in a script to be added to First Person Player, but instead I get




Unknown identifier ('QuantumCold_B').



Here is my script:


function Update () {
transform.RotateAround(QuantumCold_B.position, Vector2,20 * Time.deltaTime);
}

Also is position the right way to get the Vector position on QuantumCold_B?



Answer



Since QuantumCold_B is not defined as a variable, you won't be able to use it that way.



If "QuantumCold_B" is the name of the object in the editor, you can use the GameObject.Find function to get the game object that has the name you want.


So, you would use:


var myObject : GameObject;
// This will return the game object named Hand in the scene.
myObject = GameObject.Find("QuantumCold_B");

Then, to get the position you'd use:


myObject.transform.position

I suggest you familiarize yourself with the scripting reference in general to find a lot of these types of answers on your own. Good luck!



No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...