Selecting one instantiate prefab
I am working on a squad size rts in 2d. I have some troop prefabs that you can spawn with a button but when I click on one of them all of them get selected. I need help getting only one of these instantiate prefab to be selected at on time.
public bool Selected ()
{
Vector2 origin = new Vector2 (Camera.main.ScreenToWorldPoint (Input.mousePosition).x,
Camera.main.ScreenToWorldPoint (Input.mousePosition).y);
RaycastHit2D hit = Physics2D.Raycast (origin, Vector2.zero, 0f); //casts ray to hit somthing
if (hit) {
return true;
}
else
{
return false;
}
}
void Update ()
{
if (Input.GetMouseButtonDown (0)) // get input from the mouse
{
if (select == false) //checks if the unit is selected
{
select = Selected ();
}
else
{
Debug.Log ("error 4");
target = Camera.main.ScreenToWorldPoint (Input.mousePosition);
target.z = transform.position.z;
if (move == false)
move = true;
Instantiate (point, target, Quaternion.identity);
select = false;
}
}
I am not sure want I am missing in my code to just select one of the instantiate prefab. please help.
Answer by tormentoarmagedoom · Jun 05, 2018 at 10:23 AM
Good day.
When you instantiate something, you can store the instantiated gameobject in a GameObject variable. Like this:
GameObject ObjectInstantiated = Instantiate (prefab, position, rotation);
So now, you can access that object as any other object, for example:
ObjectInstantiated.GetComponent<NavMeshAgent>().SetDestination(destination);
or
if (ObjectInstantiated.transform.position.x >= 25)
{
Destroy (ObjectInstantiated);
}
Bye!
Your answer
Follow this Question
Related Questions
How to selected objects drawing a box like in rts games 1 Answer
How to spawn prefabs with the same speed as the prefabs spawned before? 0 Answers
Want to instantiate Prefab in its parent. 1 Answer
Everything is appearing behind camera background 0 Answers
How to instantiate various prefabs above a sprite and center them. 0 Answers