- Home /
Instantiated GameObject's components are disabled
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?
Answer by NeverHopeless · Jul 31, 2015 at 06:12 AM
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";
}
I got a compile error saying "Cannot implicitly convert 'UnityEngine.Objecy' to 'UnityEngine.GameObject'. An Explicit conversion exists (are you missing a cast?)"
I missed the typecast to (GameObject)
. Please try now.
Im very sorry. I am new to this. where would the typecast fit and how would it look?
Check the edited code i was talking about line 2. i have already fixed that. try now.
So I tried your new code but when it collided with 'Wall' i got an error saying "The variable of Sphere in CollisionAndResetSystem doesn't exist anymore. You probably need to reassign the Sphere variable of the 'CollisionAndResetSystem' script in the inspector."
Answer by nullgobz · Jul 31, 2015 at 01:06 AM
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;
Answer by rohankad · Jul 31, 2015 at 04:58 AM
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.