- Home /
Make an object appear in a specific position
Hi there! I'm developing a game where I have to place the fruit, which is on the table, on the proper plate. I would like to write a C# code so that if a fruit falls on the floor it will reappear on the table in its original position. Can someone help me?
I wrote this code, but it doesn't work and I think it's incomplete. using UnityEngine; using System.Collections; using UnityEngine.UI;
public class SpawnObject: MonoBehaviour {
public GameObject spawnObjectPrefab;
void OnCollisionEnter(Collision collision) {
if(collision.gameObject.tag == "floor")
{
Invoke("Spawn");
}
}
void Spawn()
{
Instantiate(spawnObjectPrefab, Vector3.zero);
}
}
Answer by Cronabot · Jul 17, 2020 at 05:46 PM
If I understand the question correctly you want to get the position at the start of the game i.e in the void Awake() method and set that position to a private variable named Vector3 originalPos or something. Then when you respawn the fruit, you can use Instantiate(spawnObjectPrefab, originalPos). Once you have done all that your code should look something like this:
public class SpawnObject: MonoBehaviour {
public GameObject spawnObjectPrefab;
private Vector3 originalPos;
void OnCollisionEnter(Collision collision) {
if(collision.gameObject.tag == "floor")
{
Invoke("Spawn");
}
}
void Spawn()
{
Instantiate(spawnObjectPrefab, originalPos);
Destroy(gameObject)
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Object Pickup and Respawn unity 0 Answers
Object Spawner 1 Answer
Why doesent my code get executed? 1 Answer