how to assign a object from scene as variable in script?

my main player gets instantiated through script and when the game starts he gets spawned as player(clone) in the scene, and i have this gun turret which will target player, for it to work it needs a target transform, which i add by pausing the game and dragging and dropping the clone to the target variable, i need to know how to make the target variable get the target from scene.

public Transform GTarget = GameObject.Find("Player(Clone)");

i tried few things it didnt work out :frowning:

Hi Chamakchallo,

Let’s try this. Perhaps it’s what you’re looking for:

using UnityEngine;
using System.Collections;

public class stopbubbles : MonoBehaviour {

	public GameObject Bubbles ;

	void Update () {
		if (!bubblesturnonoff) {
		Bubbles.SetActive(false);
		}

You see, it’s super-easy! Just make a variable of the “GameObject” type, (line 6 in the code) and give it the same name (in this case, my GameObject’s name was Bubbles) as the Gameobject, and then you can access the features of the GameObject, by using the name of the GameObject, then a period (dot) . and you’ll get a whole menu pop-up in Mono develop, showing what’s available. (line 10 in the code)

Hope this makes sense. (Code’s in C#)

you are assigning GameObject to a reference of Transform.
you should do:

public Transform GTarget = GameObject.Find("Player(Clone)").transform;

There are some problems. Since you are using the “public” access modifier, I assume you are declaring the variable in the field. And you can’t call GameObject.find from there, it has to be inside a method.

I actually suggest that you send the transform from the instantiated player clone on a script it has attached(So put it on the prefab). For example:

void Start () {
		TurretScript script = GameObject.Find ("Turret").GetComponent<TurretScript>(); //Gets the script attached to the Turret
		script.GTarget = gameObject.transform; //Sets the gTarget variable to the transform of the current instance of player.
	}

That way each time a new player spawns, it will automatically tell the turret that it’s supposed to target the new transform.

(TurretScript should be exchanged with the name of your Script on the turret.)

(Turret should be exchanged with the name of your turret gameobject in the scene)