- Home /
How to move a Game Object from a script not attached to it.
Hi I am making a Soccer 2D Game and I seem to have a problem with everything I try to implement if you can see my former posts haha. But my newest problem is that I want it so when my net is collided with by the soccer ball (which will add 1 to the score) I want it to reset all of the characters positions. From what I understand the way to do that would be to use the transform function to change the position of the player and the ball. But since (from my very limited knowledge) I believe that you can only use the transform function if the script is attached to the player. But the script where the ball collides with the net is attached to the net. Please give me some insight on how to move the player to his starting location when the ball collides with the net (or when +1 is added to the score, whatever you believe would be easiest)
Answer by Tehnique · Jul 10, 2014 at 07:55 PM
You can use GameObject.Find("Player") to find the player object from the net. That returns a GameObject which has a transform component.
using GameObject.Find() for anything in runtime is generally a bad idea as it is very performance intensive call. All you need to do is cache the player object in the editor (Note: This is only in case you are not generating the player object at runtime). Just add a public field and drag & drop the player object in the editor.
In case you have a player object instantiated with a prefab, you can do this ins$$anonymous$$d. (Note that the player is cached in Start, so that you can use this reference to player later, without calling "find" every time you need that object.)
public GameObject player;
void Start(){
// Use this if your player is a clone of a prefab //instantiated at runtime (Don't forget to tag your prefab).
player = GameObject.FindGameObjectWithTag("Player");
}