- Home /
I cannot get my code to function correctly, and do not know what to do. Please help.
am trying to make a cannon, that once activated, fires at a fixed rate, however when I apply my C# code to my Empty Game Object, none of my public variables appear and I cannot adjust Velocity, apply my cannonball prefab, or anything. I cannot even start the game as it says all complier errors must be resolved. i do not know what I have messed up on. pleas someone check my code and give me tips.
using UnityEngine;
using System.Collections;
public class cannonball : MonoBehaviour {
public Rigidbody projectile;
public int throwPower;
public int fireRate;
public int nextFire;
// Use this for initialization
void Start () {
projectile = projectile.GetComponent<Rigidbody> ();
}
// Update is called once per frame
void Update () {
if (Input.GetButtonDown ("Horizontal")&&Time.time>nextFire) {
nextFire = Time.time + fireRate;
Rigidbody clone = Instantiate (projectile, transform.position, transform.rotation);
clone.velocity = transform.TransformDirection (Vector3.forward * throwPower);
}
}
}
2 things to try:
format ALL of your code.
post the errors from the console (including line numbers - that's why formatting all of the code is important)
Answer by Landern · Mar 25, 2015 at 02:03 PM
You should ALWAYS post the errors from the console.
That said, you're probably getting a casting error.
When you Instantiate a game object, it returns UnityEngine.Object, you are trying to stuff that object into a Rigidbody variable called "clone". If you want to do this you have to explicitly state that this new object(clone) is also a Rigidbody by casting it.
Change line 24 to:
Rigidbody clone = (Rigidbody)Instantiate (projectile, transform.position, transform.rotation);
It is implied, but probably worth emphasising that it's the compiler errors that are the problem here. Until you've got it building, all the stuff about not being able to adjust the field values etc is by-the-by.