Call function for instantated prefab. "Object reference not set"
Hello !
First post on the forum, I just just started to play with Unity (I love it so far), but I'm a little bit lost sometimes.
My current problem is the following : I have a Player
and who can shoot Bullet
. For that I have created a prefab for each object, and associated a script for each prefab (`Player.cs` and Bullet.cs
, respectivitely). I was doing it alright at first, but only in one direction (to the right). Now, I would like to shoot bullet in the direction based on the player position, so I had to refactor my code a little.
Ideally, I would like to call a Shoot
function from the Player
script, which will Instantiate a bulletPrefab
, and call a Fly
function from the Bullet
script, which will take the player's position to decide the direction.
Here is Player.cs
:
public class PlayerController : MonoBehaviour
{
public bool isMovingForward = true;
public GameObject bulletPrefab;
private void Shoot()
{
GameObject bullet = Instantiate(bulletPrefab, ..., ...);
Bullet bulletController = bullet.GetComponent<Bullet>();
bulletController.Fly(isMovingForward);
}
}
And Bullet.cs
public class Bullet : MonoBehaviour
{
private Rigidbody bulletRb;
void Start() {bulletRb = GetComponent<Rigidbody>();}
void Fly(bool isForward) {bulletRb.AddForce(getForceVector(), ForceMode.Impulse);}
Vector3 getForceVector() {...}
}
That ... doesn't work. I get NullReferenceException: Object reference not set to an instance of an object Bullet.Fly (System.Boolean isForward) (at Assets/Scripts/Bullet.cs:31)
Would you be able to help me understand what's going on ? Also, if you think I'm not doing it the right way, I'd love to here some suggestion, I'm very new to all of this.
Thanks !
Answer by cazoulable · Dec 23, 2020 at 05:18 PM
I solved my own problem, by getting the player direction in the bullet controller. I don't know why I wanted to make it "so" complicated...
public class PlayerController : MonoBehaviour
{
public bool isMovingForward = true;
public GameObject bulletPrefab;
// Shoot
private void Shoot()
{
Vector3 dropletSpawnPos = transform.position;
GameObject bullet = Instantiate(bulletPrefab, dropletSpawnPos, bulletPrefab.transform.rotation);
}
}
and
public class Bullet : MonoBehaviour
{
public bool isGoingFoward = true;
private Rigidbody bulletRb;
private PlayerController playerController;
// Start is called before the first frame update
void Start()
{
bulletRb = GetComponent<Rigidbody>();
playerController = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerController>();
isGoingFoward = playerController.isMovingForward;
}