Question by
yang_xiong · Sep 20, 2015 at 03:06 AM ·
c#nullreferenceexception
got trouble:object reference not set to a instance of an object
using UnityEngine;
using System.Collections;
public class shoot : MonoBehaviour {
public Rigidbody2D bullet;
public float shoot_interval=0.3f;
float cur_interval ;
// Use this for initialization
void Start () {
cur_interval = 0;
}
// Update is called once per frame
void Update () {
if (Input.GetKey (KeyCode.H)) {
cur_interval -= Time.deltaTime;
if(cur_interval<0){
cur_interval = shoot_interval;
Rigidbody bul = Instantiate(bullet,transform.position,transform.rotation) as Rigidbody;
if(this.GetComponentInParent<playerControl>().faceright==false){
//Debug.Log("left");
Vector3 vec= new Vector3(-1*transform.localScale.x,transform.localScale.y,transform.localScale.z);
bul.transform.localScale = vec;
}
else{
//Debug.Log("right");
}
}
}
}
}
When I press H I want to create a bullet which is a prefab, and I've already drag it to the inspector The error shows up at the line "bul.transform.localScale = vec;" and I don't know why. Any body help? How should I change my code?(the if-else sentence is used to change the direction of the bullet. I can initiate the bullets but can not change the direction of the bullet because of this error.)
Comment
Answer by yang_xiong · Sep 20, 2015 at 03:36 AM
i found the problem, Rigidbody bul = Instantiate(bullet,transform.position,transform.rotation) as Rigidbody; should be changed to Rigidbody2D bul = Instantiate(bullet,transform.position,transform.rotation) as Rigidbody2D; :)