- Home /
Instantiate specific object from "FindGameObjectsWithTag" Array
So, Im trying to instantiate some objects to my canvas, somethis like this:
I made two scripts. The first is located into my scene objects and is so simple:
public class Objects : MonoBehaviour
{
public GameObject _prefab;
}
And the other one is on an emty object inside my canvas:
public GameObject[] _objects;
GameObject _player;
[SerializeField]
GameObject _cameraUI;
bool _IsCreated;
void Start()
{
_objects = GameObject.FindGameObjectsWithTag("Special_Objects");
_player = GameObject.Find("FPSController");
_cameraUI.SetActive(false);
_IsCreated = false;
}
void Update()
{
foreach (GameObject _specialObject in _objects)
{
if (Vector3.Distance(_player.transform.position, _specialObject.transform.position) <= 2 && Input.GetKeyDown(KeyCode.E) && !_IsCreated)
{
GameObject specialObject = Instantiate(_specialObject.GetComponent<Objects>()._prefab, transform.position, _specialObject.GetComponent<Objects>().transform.rotation);
specialObject.transform.localScale = new Vector3(10, 10, 10);
_player.SetActive(false);
_cameraUI.SetActive(true);
_IsCreated = true;
}
else if (Input.GetKeyDown(KeyCode.R) && _IsCreated)
{
_player.SetActive(true);
_cameraUI.SetActive(false);
_IsCreated = false;
}
}
}
}
But there's something wrong. This is what is happening:
What I want is just when player is close to an especific object, the code instantiate his respective prefab but I dont know how to do that.
Good day.
I see you instantiate a Prefab stored in a script in another component. I never tried this, but i supose i should work.
Whats the problem ? Is the execution instantiating something? not? Are you sure the code reaches that line? Is instantiating something diferent? or at diferent position? or what?
Tell us whats the exatcly problem, what are you sure is working, what you dont know, what you need.. etc.. thx
Yeah I think my code is instantiating but all the objects, not just the specific object that I want to instantiate. As you can see on the second picture, there are two objects instantiated. I want to pick one object, instantiate his prefab and when input "R" disable this.
Your answer
Follow this Question
Related Questions
finding clones and destroying them doesn't work 0 Answers
How can I instantiate gameobjects from an array in a specific order? 1 Answer
How to learn amount of objects in selected prefabs folder? 0 Answers
Instantiating prefab at child (spawnlocations are arrays) 2 Answers
How to Instantiate a GameObject from a ScriptableObject piece of script? 0 Answers