- Home /
Problems with instantiating a clone as a child?
I am having problems with code I am writing that applies particles to objects hit by my projectile. Everything but the parenting works fine, the clone is created but is stuck at the position it was instantiated at.
Getting
NullReferenceException: Object reference not set to an instance of an object
ProjectileScript.OnCollisionEnter (UnityEngine.Collision other) (at Assets/Scripts/Player/ProjectileScript.cs:32)
Heres the script:
using UnityEngine;
using System.Collections;
public class ProjectileScript : MonoBehaviour {
public bool isClone = false;
public GameObject myParticle;
void Start () {
}
// Update is called once per frame
void Update () {
if(isClone == true){
renderer.enabled = true;
Destroy (gameObject, 5);
}
}
void OnCollisionEnter(Collision other){
if(isClone == true){
if(other.gameObject.tag != "Ground"){
if(other.gameObject.tag == "Enemy"){
Transform clone;
clone = Instantiate(myParticle, other.transform.position, other.transform.rotation) as Transform;
clone.transform.parent = other.transform;
}
Destroy (gameObject);
}
}
}
}
I've tried doing clone.parent = other.transform; that doesn't work either though.
Answer by aldonaletto · Oct 10, 2012 at 05:46 PM
I'm not a C# expert, but suspect that clone should be declared as GameObject:
GameObject clone;
clone = Instantiate(myParticle, other.transform.position, other.transform.rotation) as GameObject;
clone.transform.parent = other.transform;
At least in JS, Instantiate returns a reference of the same type as the prefab, which is a GameObject in this case.
I did have to change the typecast to "as GameObject" also though
Your answer
Follow this Question
Related Questions
Instantiated GameObject collision without script repetition? 1 Answer
Instantiated Prefab's script doesn't work 2 Answers
How do I get the global position 2 Answers
Ignore parent Rotation 1 Answer