Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Hi, I have a gameobject Instantiate postion problem

Discussion in 'Getting Started' started by ing_unity, Jan 7, 2022.

  1. ing_unity

    ing_unity

    Joined:
    Nov 30, 2020
    Posts:
    12
    I use simple code to Instantiate a new gameobjet, which do not setting it postion and rotation
    var newObj = UnityEngine.Object.Instantiate(prefab, parent);
    Why the newObj postion is diffrent than the position I saw the prefab in inspector, especially in gaming I drag the prefab under the same parent as newObj, the position is correct.
    I'm very confused and need some help. Many thanks!
     
  2. Tamoooooo

    Tamoooooo

    Joined:
    Sep 24, 2020
    Posts:
    8
    Hi, i dont think its good practise to instantiate a prefab because of its position, i would rather use a normale gameobject and activate and deacitve it with gameObject.setActive(true); if you know the position and just want to instantiate it one time

    If you plan to instantiate multiple prefabs at the same position (lets say to spawn bullets out of your weapon) i would suggest making a reference to the transform where you want your gameobjects to spawn and then call the spawnpoint.position on instantiating. Something like that:

    public Transform spawnPoint; //You need to set this in the inspector
    //And then this where you want to spawn you prefab:
    Instantiate(prefab, spawnPoint.position, spawnPoint.rotation, parent);
    //you can also use this, but you only need to do this, when you want to access the prefabs functions after instantiation
    GameObject prefabGo = Instantiate(prefab, spawnPoint.position, spawnPoint.rotation, parent);
    prefabGo.GetComponent<YourScript>().YourFunctionYouWantToCall(someParametersYouWantToPass);
     
  3. ing_unity

    ing_unity

    Joined:
    Nov 30, 2020
    Posts:
    12
    I found my problem due to cinemachine follow target, I'm not fully understanding about cinemachine, thanks!