- Home /
Spawn an object with additional parameter
Hello,
I just wanted to start my first project in Unity.
What I wanted to achieve is a simple game, where you move around the sphere and dodge obstacles falling from the sky.
Now I have a script that adds gravity to an object (what it does is that an object is getting pulled by my planet (sphere) called attractor).
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class FauxGravityBody : MonoBehaviour {
private FauxGravityAttractor attractor;
private Rigidbody rb;
public bool placeOnSurface = false;
void Start ()
{
rb = GetComponent<Rigidbody>();
attractor = FauxGravityAttractor.instance;
}
void FixedUpdate ()
{
if (placeOnSurface)
attractor.PlaceOnSurface(rb);
else
attractor.Attract(rb);
}
}
And I also have a script that randomly spawns objects:
using System.Collections;
using UnityEngine;
[RequireComponent(typeof(FauxGravityBody))]
public class Spawner : MonoBehaviour {
public GameObject meteorPrefab;
public float distance = 20f;
void Start ()
{
StartCoroutine(SpawnMeteor());
}
IEnumerator SpawnMeteor()
{
Vector3 pos = Random.onUnitSphere * 60f;
Instantiate(meteorPrefab, pos, Quaternion.identity);
yield return new WaitForSeconds(1f);
StartCoroutine(SpawnMeteor());
}
}
Now, while each spawned object requieres "FauxGravityBody" attribute - it doesnt spawn with it.
So basically what I want to achieve is that each spawned object on default has "FauxGravityBody" attribute attached to it.
What would be the best way to achieve this?
Kind regards.
Answer by Namey5 · Feb 17, 2020 at 12:35 AM
The 'Instantiate' function actually returns a reference to the object that has just been created. We can use that reference to add new components to the object directly;
GameObject go = Instantiate(meteorPrefab, pos, Quaternion.identity);
go.AddComponent<FauxGravityBody>();
Similarly, if you needed immediate access to that new component, the 'AddComponent' function also returns a reference to the component that was added.
However, because you are using a prefab for instantiation, all of this is unnecessary. If you want new objects to spawn with that component added, all you need to do is add the component directly to the prefab itself in the editor.