After I instantiated a Game Object (Sphere), it receives a new name (Sphere (Clone)) and all of its components are disabled except for the mesh renderer.
using UnityEngine;
using System.Collections;
public class CollisionAndResetSystem : MonoBehaviour {
int score = 0;
public GameObject Sphere;
public Transform sphere;
void OnCollisionEnter2D(Collision2D coll) {
if (coll.gameObject.tag == "Player") {
print ("hit");
Application.LoadLevel (0);
print(score);
}
if (coll.gameObject.tag == "Wall") {
print ("jumped over");
score++;
print(score);
Respawn ();
}
}
void Respawn(){ //Respawns the sphere
Destroy(gameObject);
Instantiate(Sphere, new Vector3(9, 1, 0), Quaternion.identity);
Sphere.name = "Sphere"; //Here is where i tried to fix the problem with the name "Sphere" turning into "Sphere(Clone)"
}
}
How do I go about instantiating Sphere while keeping all of its components activated, or rather activating its components in the script?
Drag drop your prefab to scene and in the inspector make sure your prefab have all its childs active and press Apply
. Then try re-spawning like this:
GameObject sphereInstance;
void Respawn(){ //Respawns the sphere
// Destroy the currently allocated sphere, so re-spawn can be done.
Destroy(sphereInstance);
sphereInstance = (GameObject)Instantiate(Sphere, new Vector3(9, 1, 0), Quaternion.identity);
// Change name of the instance instead of Prefab itself
sphereInstance.name = "Sphere";
}
Change the prefab Sphere object to whatever you want.
It will be created per your definition.
Or set it in code like this:
GameObject go = (GameObject)(Instantiate(Sphere, new Vector3(9, 1, 0), Quaternion.identity));
go.GetComponent<SomeComponent>().enable = true;
Enable the Sphere in your scene, apply changes to the prefab.
Then disable it. Don’t disable and apply the changes.
If you do, it will be disabled by default.
What has worked for me has been to change the order, to first urge the object and then destroy it.
Its Likely that there is an exception being thrown in either the Awake or Start Methods leading the component to being auto disabled