- Home /
How do I acces a specific GameObject within the terrain????
How do I acces a specific GameObject within the terrain????
I had developed a small terrain that spawning a number of enemys in random locations. However the clones that are spawned have Missing (GameObject)
However my Enemy script its attached below. Note that the script its working fine when the enemy is in the Hierarchy as an 'Object' instead of a clone:
public GameObject target;
public Animator animator;
public AudioSource attackAudio;
// Use this for initialization
void Start()
{
animator = GetComponent<Animator>(); //Default Animator IDLE
attackAudio.Stop();
}
// Update is called once per frame
void Update()
{
. . .
}
What should i set to my to my for loop to get a specific GameObject??
Answer by PizzaPie · Nov 25, 2017 at 09:54 PM
Prefabs can not hold any scene references so you ll have to fill the target field on runtime. Here are couple ways:
On the Spawn_Objects_Script hold a reference of the target and feed it to each clone , don't forget to fill the reference of the Spawn Object on the inspector.
//... public GameObject target;
//and when you instantiate //... GameObject enemy = Instantiate(...); enemy.GetComponent<Enemy>().target = target;
Use FindObjectOfType on the Enemy Script (kinda bad)
//on Enemy Script //... void Start(){ target = FindObjectOfType(); } //target type should be a class used only on Target GameObject
And on your target ,ex. if target is player and has a player script add on it this
public class Player : MonoBehaviour{ public static Player instance;
void Awake(){ instance = this; }
and on the Enemy script
//
public GameObject target;
void Start(){
target = Player.instance.gameObject;
}
First one is the most sound one. Cheers.
Your answer
Follow this Question
Related Questions
How do I acces a specific GameObject within the terrain???? 0 Answers
Get unity to recognize prefab in C# 2 Answers
Assigning id to instantiated objects 1 Answer
Instantiate ID 2 Answers