So I’m having a lot of trouble calling a function from another script. The script that the function is in, is always null (I’ve tested). I need it not to be null so the function can be called. So, the script that I’m trying to access is attached to a prefab in my assets folder, I’m pretty sure that that’s the problem, but I don’t know how to fix it. Please help me.
(I cut all of the irrelevant stuff out of the scripts)<<<<<<<<
Script I’m trying to call the function from.
public class Glock18Firepoint : MonoBehaviour {
private BulletTrail bulletScript;
void Awake()
{
bulletScript = FindObjectOfType<BulletTrail>();
}
public void Shoot()
{
{
Debug.Log("is bulletScript null? " + (bulletScript == null));
if (bulletScript)
{
bulletScript.Move();
}
}
}
Script I’m trying to access.
public class BulletTrail : MonoBehaviour {
public void Move()
{
//My code here
}
}
My best guess would be its null because you calling the FindObjectOfType function in the Awake function.
Awake is called right as an object is created so if the Glock18FirePointer is being spawned before the BulletTrail causing the findobject to return null(because the bullet trail isn’t spawned at that point). Remember if you have two objects being soawned at the sametime in reality, one has to be created before the other, that is why start is usefull because it waits for all other objects to initialize.
Solution: call FindObjectOfType in Start() function or ensure that there is a bullet trail in existance when the Glock is spawned
Hey, just to make sure: is the prefab with the tryed-to-be-accesses script has an instance in your scene? because if it doesn’t I’m pretty sure you won’t be able to retrieve it using “FindObjectOfType”. I would try having an instance of that prefab in your scene and then running. Alternatively, you can define a reference to your wanted script in your caller script, and drag it in the inspector.
YES!!! I did it, I re-did my whole system pretty much, I deleted all my code on the script trying to access that one script, then I got rid of the script I was trying to access and put the code from that script onto the script were I had deleted the code/ the one I was trying to call the function from. And I changed the code to make it work… And deleted another script I was using that was attached to my player that was calling a function in the script that I was trying to call that one function from. Its sooo confusing to explain. as i’m typing this I’m realizing you probably have no idea what I’m trying to say. SO BASICALLY, I had a script attached to my player, I had a script attached to my “FirePoint” (spawner), and another script attached to the bullet prefab itself. And NOW I just have ONE script attached to my spawner/ “FirePoint”.
Dust-Cloud and LegionStudios, you both helped realize what the problem was and helped me come to this conclusion thank you so much.