I am an extreme noob who is in my first week of Unity & C# and in between reading and watching videos I have been trying to make myself a simple archer.
I have some code that I have been working on:
public class ArrowShooter : MonoBehaviour {
private GameObject arrowPrefab;
void Start () {
arrowPrefab = Resources.Load ("arrow") as GameObject;
}
void Update ()
{
if (Input.GetMouseButtonDown (1)) {
GameObject newArrow = Instantiate (arrowPrefab) as GameObject;
newArrow.transform.position = transform.position;
Rigidbody rb = newArrow.GetComponent<Rigidbody> ();
rb.isKinematic = true;
if (Input.GetMouseButtonDown (0)) {
rb.isKinematic = false;
rb.velocity = Camera.main.transform.forward * 30;
}
}
}
I can get the arrow to fire if I leave out the isKinematic = true and the nested if statement and just set the velocity.
Otherwise the arrow is instantiated in the right place but is not parented to the object the script is on and will not fire.
I can see myself that the logic looks all wrong. I initially made two functions ArrowSpawner and ArrowFire like so:
public class ArrowShooter : MonoBehaviour {
private GameObject arrowPrefab;
void Start () {
arrowPrefab = Resources.Load ("arrow") as GameObject;
}
void ArrowSpawner ()
{
if (Input.GetMouseButtonDown (1)) {
GameObject newArrow = Instantiate (arrowPrefab) as GameObject;
newArrow.transform.position = transform.position;
Rigidbody rb = newArrow.GetComponent<Rigidbody> ();
rb.isKinematic = true;
}
}
void ArrowFire () {
if (Input.GetMouseButtonDown (0)) {
rb.isKinematic = false;
rb.velocity = Camera.main.transform.forward * 30;
}
}
}
But ArrowFire couldn’t find the rigidbody from ArrowSpawner. So I tried to define the rigidbody in void Start (), which allowed me to compile but did nothing in the game. I thought this was because I was missing void Update () which led me back to the first piece of code.
I know I need to do a lot more reading before I can make any meaningful progress scripting. But can someone tell me the correct way to say:
if (Input.GetMouseButtonDown (1)) the rigidbody is kinematic (& parented to the game object the script is attached to)
then when: (Input.GetMouseButtonDown (0)) the rigidbody in not kinematic and finally apply the velocity Camera.main.transform.forward * 30.
Thanks for taking the time to read this. I hope I was clear in my question.