Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Call a function from a script that is attached into a prefab gameobject

Discussion in 'Scripting' started by Pavlos_Mavris, Oct 5, 2020.

  1. Pavlos_Mavris

    Pavlos_Mavris

    Joined:
    Sep 17, 2018
    Posts:
    57
    Hello everyone,

    I have a question about prefabs, first I'm trying to call a function/method from a script that is attached into a prefab gameobject but all the time I get an error "NullReferenceException: Object reference not set to an instance of an object". Is there a way to call functions from a prefab gameobject?

    A real example is that I have my player(GameObject) which is also a prefab and I have a script on it which is called "Player Movement" and inside that script I have a function called "SecondCgance()" which basically if the player dies and the function executes it will resets the players position and resets some other components that are needed. Now I want to call that function from a different script which is called "AdsManager" and the player will watch an advertisment of 30 seconds and if it finished successful the "SecondChance()" function will be executed. I try a few ways to call the function by trying to find the object with a tag and then get the script component and then execute the function, I tried to make the prefab as a singleton with an instance but nothing works, and I get all the time the same error.

    If anyone has a solution to that or maybe something that we can try I would be glad to see it!
    Thank you for your time!!
     
  2. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    Your prefab and you instantiated player are not the same objects. The player is an object created from the template which is the prefab. It sounds like you want to get the player object and access a script on that.

    You can do that many ways, you can use FindObjectOfType and look for the script if it is the only one in the scene, you can store a reference to the player somewhere and get it from that or tag the player object, look for the object with that tag and then the script as well as a few other ways. How you do it depends on how your game structure is working currently.
     
  3. Pavlos_Mavris

    Pavlos_Mavris

    Joined:
    Sep 17, 2018
    Posts:
    57
    Thank you for the reply, that actually helped me!!