Game Manager can't decide what the instance of the object is despite just making an instance of it
Problem: Unity is giving me this error:
NullReferenceException: Object reference not set to an instance of an object GameMangerController.Start () (at Assets/Scripts/GameMangerController.cs:17)
And that problem is with this code, (bolded line 17):
public class GameMangerController : MonoBehaviour {
public GameObject ballPrefab;
private Ball currentBall;
// Use this for initialization
void Start()
{
GameObject ballInstance = Instantiate(ballPrefab, transform);
currentBall = ballInstance.GetComponent<Ball>();
**currentBall.transform.position = Vector3.zero;**
}
}
with my relevant Ball.cs being:
public class Ball : MonoBehaviour {
public float minXSpeed = .5f;
public float maxXSpeed = 1.5f;
public float minYSpeed = 0f;
public float maxYSpeed = 1.5f;
Rigidbody2D ballRigidBody;
// Use this for initialization
void Start () {
ballRigidBody = GetComponent<Rigidbody2D>();
ballRigidBody.velocity = new Vector2(
Random.Range(minXSpeed,maxXSpeed) * (Random.value > 0.5f ? -1 : 1),
Random.Range(minYSpeed, maxYSpeed) * (Random.value > 0.5f ? -1 : 1)
);
}
}
Attempt at Solution:
And I have checked that all my filenames are correct and that I dragged the prefab to the correct public area on the GameManager. In the scene, there is no ball object, the only ball object is the one instantiated by the GameManager.
Rewrote the code for GameManager and Ball a few times to ensure there were no typos.
Notes: I am pretty new to C# and Unity in general, so I've been following tutorials on how to get started. This same issue presented itself to me in a previous project, but I was never able to fix it there either.
Answer by Vicarian · Jan 07, 2019 at 07:07 PM
The only things I can think of is that the prefab you're trying to instantiate doesn't actually have a Ball script attached, that you changed or otherwise moved the script such that the reference to the script in the prefab got broken, or the ballPrefab value in the Manager script was never set a value. Are you getting any messages like "MonoBehaviour attached to object x in scene y couldn't be loaded" or "The object you want to instantiate is null?"
The prefab does have a script attached to it https://imgur.com/a/hxDae9t
I'm not getting any errors besides the one
Aha, the ball script doesn't live directly on the object you're trying to instantiate. It's on a child transform, so you can use ballInstance.GetComponentInChildren<Ball>()
to resolve the reference.
Would this also work for children of children?