Spawning a Ball going forward every 5 seconds error, help!
Alright so I made this script:
using UnityEngine;
using System.Collections;
public class CannonShots : MonoBehaviour {
public Transform ballPos;
public Rigidbody Ball;
public float timeMin = 1;
public float timeMax = 3;
public float forceAmount = 1500;
void SpawnBall()
{
Rigidbody ballRigid;
ballRigid = Instantiate(Ball, ballPos.position, ballPos.rotation) as Rigidbody;
ballRigid.AddForce(ballPos.forward * forceAmount);
}
void Start() {
float timeToSpawn = Random.Range(timeMin, timeMax);
InvokeRepeating("SpawnBall", timeToSpawn, timeToSpawn);
}
}
An error pops out saying NullReferenceException: Object reference not set to an instance of an object CannonShots.SpawnBall () (at Assets/MyAssets/Scripts/CannonShots.cs:16) . I know what this error means but I can't seem to figure out how to fix it. So can somebody please help me and explain what the error was and correct it? Thanks!
Answer by TBruce · May 08, 2016 at 07:04 PM
The following fixes your error(s) and adds some debugging
void SpawnBall()
{
Rigidbody ballRigid;
if ((Ball != null) && (ballPos != null))
{
ballRigid = Instantiate(Ball, ballPos.position, ballPos.rotation) as Rigidbody;
if (ballRigid != null)
{
ballRigid.AddForce(ballPos.forward * forceAmount);
}
else
{
debug.LogWarning("The instantiated item does not contain a Rigidbody");
}
}
else
{
if ((Ball == null)
{
debug.LogWarning("Ball has not been assigned. Please assign the Ball");
}
if (ballPos == null)
{
debug.LogWarning("ballPos has not been assigned. Please assign the ballPos");
}
}
}
Also if you want to spawn every 5 seconds you need to do it like this
InvokeRepeating("SpawnBall", timeToSpawn, 5);
Thanks, this did it! I'm really new to Unity scripting and C# overall, do you $$anonymous$$d telling me the faults in my script?
@TheReal$$anonymous$$uha
As previously mentioned to repeat the spawn every 5 seconds you needed a value of 5 as the last parameter not timeToSpawn
You were trying to instantiate an object without validating that you had a valid prefab and transform
You were trying to use ballRigid after instantiating an object without validating it
Answer by Dext · May 08, 2016 at 06:41 PM
Have you assigned an object to the "ballPos and Ball" variables in the inspector ? I think the variables have a value of NULL. That is why it is called a NullReferenceException error.
Yes I have, but it still gives me the error. I can play the scene but after the object spawns it pauses the game and prints the error. I can play it if I turn off the error pause but I worry it will become an issue later on.