Instantiate and remove objects according to the number of objects in an Array
hello everyone , i got a bit of a problem , here it is:
i want to create a radar , where it have a range , and some planets , what i want is as follows:
1:-when a planet enters the range (lets say 100) its added to an array (Done)
2:-spawn a UI image object for each planet in range , so if there is 3 planets in range then spawn only 3 , if 2 then spawn 2 .....etc
3:-if a planet leaves the range , then its corresponding icon gets remove (maybe Disabled).
4:-make each icon follows its corresponding planet (will try to do it on my own at first)
problem: using the script below , its just adds unlimited number of Icons.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Radar : MonoBehaviour {
public float radarRange;
public LayerMask planets;
public Collider[] hits;
public Slider range;
public Image icon;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void FixedUpdate () {
//Collider[] hits;
hits = Physics.OverlapSphere(transform.position, radarRange, planets);
radarRange = range.value;
foreach (Collider planetObject in hits)
{
if (Vector3.Distance(transform.position, planetObject.transform.position) < radarRange)
{
Instantiate(icon, planetObject.transform.position, Quaternion.identity);
}
}
}
}
i know it might look like a beginner script , but i am just learning to script.
thanks for any help i get.
Answer by TheSorm · Apr 24, 2016 at 02:38 AM
Look at this: http://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html Your code dont work because the collider is called every fixed update and look if ther is a collsion but the collision dont stop after one collison so many instanzien get startet. If you would use Collider.OnTriggerEnter and Collider.OnTriggerExit it would just called once.
hmm , thanks for the respond , but i don't see how this gonna help me , as for the detection of planets , i am using Physics.OverlapSphere, not a normal collision detection.
anyway thanks for your time
if you use Triggers its way easyer to detect when an object enter and leaf your radius.
Your answer
Follow this Question
Related Questions
How can i Instantiate gameobject in array 0 Answers
Adding a new GameObject to an Array without overriding the others 0 Answers
Can I spawn with an array in order? 2 Answers
How do I destroy a instantiated UI image that is a prefab but pushed the canvas? 0 Answers
Need Help instantiating GameObjects in an array using the middle mouse wheel. whew. 1 Answer