Hello,
I am having trouble with my code and using Unity. I want to make it so that when you click the mouse button, a ball is fired and hits a target. I think I am getting pretty close. The only error coming up is Object reference not set to an instance of an object. I'm not sure what exactly is causing this. I'll post my code. It says its coming from line 37, which is rbBall.AddForce(trans.forward * Speed); I'm not sure what is causing this to be. Note that this game is 2D, but since the ball is shot from the camera, the ball is set to be shot from the Z axis and has 3D physics rigidbody attached to it.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class PlayerBall : MonoBehaviour {
public Text Dunks; //text used to show dunks
//public Transform ballPrefab; //ball position
public float Speed = 1000f; //speed of ball
GameObject BallPrefab;
private int iDunks; //number of dunks
public Transform trans;
private int Balls = 4;
private Texture2D ballimg;
void Start () {
//Dunks.text = "";
iDunks = 0;
BallPrefab = GetComponent<GameObject>();
trans = GameObject.Find("Player").transform;
BallPrefab = GameObject.Find("Player");
ballimg = Resources.Load("Player/ball.png") as Texture2D;
}
// Update is called once per frame
void Update () {
float h = Input.GetAxis ("Horizontal") * Time.deltaTime * Speed;
float v = Input.GetAxis ("Vertical") * Time.deltaTime * Speed;
if (Input.GetMouseButton (0) || Input.GetButton ("Fire1") )
{
Rigidbody rbBall;
BallPrefab.SetActive(true);
rbBall = Instantiate(BallPrefab,trans.position,trans.rotation) as Rigidbody;
rbBall.AddForce(trans.forward * Speed);
iDunks++;
Balls--;
Dunks.text = iDunks.ToString();
}
}
}