How to control an object after clicking on it?
I have a cannon i want to control (control the angle and shoot it) but not when i start the scene. Only after right clicking on it. I tried it like this:
public class Shoot : MonoBehaviour
{
private float angle;
public GameObject Cannon;
public Text angleText;
// Update is called once per frame
public Rigidbody projectile;
public float horizontalSpeed = 2.0F;
public void Update()
{
if (Input.GetMouseButtonDown(1))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 100, 0))
{
ControlCannon();
}
}
}
public void ControlCannon()
{
float h = horizontalSpeed * Input.GetAxis("Mouse Y");
transform.Rotate(h, 0, 0);
Text();
if (Input.GetButtonDown("Fire1"))
{
Rigidbody clone;
clone = Instantiate(projectile, GameObject.Find("Firepoint").transform.position, transform.rotation) as Rigidbody;
clone.velocity = transform.TransformDirection(Vector3.up * 10);
}
}
void Text()
{
angle = Cannon.transform.rotation.eulerAngles.x - 270;
angleText.text = "Angle: " + angle.ToString();
}
}
But it doesn't do anything when i click on the cannon. Is there a different way or am i doing something wrong here?
Answer by Nomenokes · Feb 11, 2018 at 04:40 AM
Right now ControlCannon
is only being called in the one tick you first click on it. If you look at line 21, it is nested within Input.GetMouseButtonDown
and only there. What you should do instead is something like this:
public GameObject cannon; //it's good practice to have variables lowercase
//...
public void Update()
{
ControlCannon(); //called every tick
if (Input.GetMouseButtonDown(1))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 100, 0))
{
cannon = hit.collider.gameObject; //you assign the cannon when it is clicked
}
}
}
public void ControlCannon()
{
float h = horizontalSpeed * Input.GetAxis("Mouse Y");
cannon.transform.Rotate(h, 0, 0); //controls the cannon
if (Input.GetButtonDown("Fire1"))
{
Rigidbody clone;
clone = Instantiate(projectile, cannon.transform.position, transform.rotation) as Rigidbody;
//...
I now get: "NullReferenceException: Object reference not set to an instance of an object" for the cannon variable in the ControlCannon(). I can't figure out how to put it in the right order to make it work.
Yeah my code was a little incomplete. cannon
will be null until it gets assigned. Do a check for null:
public void ControlCannon()
{
if(cannon==null)return;
It worked! Thank you so much, i knew it had to be something like that.