Hi, I’m a beginner to Unity and I’m trying to create a simple shooter with 4-directional movement.
When the player presses a direction on the arrow-pad, I want a bullet to spawn and move in that direction.
If the player presses the left arrow-key, then I want a bullet to spawn near the player and I want to simultaneously set the direction variable of the bullet to “left”. In the Bullet class, the Update() method holds logic that moves the bullet in the direction specified in the direction variable.
However, I’m struggling with trying to create a reference to the bullet object and altering its variables.
PlayerController variables (the Bullet prefab is added to the bullet slot in the inspector):
public class PlayerController : MonoBehaviour {
public GameObject bullet;
In PlayerController Update() function:
if (Input.GetKeyDown(KeyCode.LeftArrow)) {
Bullet b = (Bullet) Instantiate(bullet, transform.position + Vector3.left, Quaternion.identity);
b.SetDirection("left");
}
Code for Bullet class:
public class Bullet : MonoBehaviour {
public string direction;
private float bulletSpeed = 0.2f;
private float speed = 10.0f;
void Start () {
direction = "right";
}
void Update () {
if (direction == "left") transform.position += Vector3.left * speed * Time.deltaTime;
}
public void SetDirection(string bulletDirection) {
direction = bulletDirection;
}
}
The problem occurs when I press the left-arrow. I get the error for the line after if (Input.GetKeyDown):
InvalidCastException: Cannot cast from source type to destination type
I didn’t think I needed the cast to Bullet because I thought Instantiate() would return the instance of Bullet that I just made, but when I left out the cast, I got this error for that same line:
Cannot implicitly convert type ‘UnityEngine.Object’ to ‘Bullet’. An explicit conversion exists (are you missing a cast?)
And now, I’m lost. The Instantiate() method doesn’t return a type Bullet, and if I try to cast it, I get an error. How can I grab that instance of the Bullet I created with that key press and then alter its direction?
Thanks in advance for any help.