Home > Software design >  How can i spawn a prefab as a GameObject while setting some of its attributes?
How can i spawn a prefab as a GameObject while setting some of its attributes?

Time:10-03

I am making a 2D game in unity and I am trying to spawn a prefab via a "spawner" script that uses instantiate() to spawn the prefab into the scene.

My problem is: This prefab contains a script that i want to access and modify some fields based on the situation (it contains a list of Vector3s that represent positions for a path to follow). I thought editing these values right as i instante the GameObject would be ideal, is there any way to do that or am i completely doing it wrong by using instanciate() for this?

my spawner class looks like this:

    public class Spawner : MonoBehaviour
    {
        [SerializeField]
        internal Vector3 spawnPosition;
        [SerializeField]
        internal Quaternion spawnRotation = Quaternion.identity;
        [SerializeField]
        internal GameObject spawnee;

        internal void spawn()
        {
            GameObject echo = Instantiate(spawnee, spawnPosition, spawnRotation) as GameObject;
    
        }
    }

I don't quite know how to access and modify the values, i just figured out how to spawn an instance of the prefab...

I'm pretty new to unity and c#, so i'd like to know the "how" but also "why" of your answers please, thanks in advance for the help :)

CodePudding user response:

You would either simply use

var yourComponent = echo.GetComponent<ComponentYouWantToAccess>();

or even easier and saver would be you use the correct type for your prefab field right away

[SerializeField]
internal ComponentYouWantToAccess spawnee;

This also makes sure you can only drag in a prefab there which actually has such component attached.

And because Instantiate is generic and returns the same type you pass in as prefab you would then simply do

var yourComponent = Instantiate(spawnee, spawnPosition, spawnRotation);
  • Related