Search Unity

Question Running Function from a script inside a prefab

Discussion in 'Scripting' started by DogBoss98, Jul 13, 2020.

  1. DogBoss98

    DogBoss98

    Joined:
    Feb 11, 2020
    Posts:
    3
    Hi, i'm new to unity and am having some trouble with calling a function from another script that is on a prefab. How would i go about referencing the prefab's script to then call the function? Any help would be greatly appreciated.
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    If it's not a static method, then you need to instantiate the prefab so it creates a copy of the object in your scene and then you access the script on that copy. You aren't normally accessing scripts on prefabs. You might need to provide more info on what you are trying to do. ie, do damage to an enemy, access health value, etc. So we can better explain things.
     
  3. DogBoss98

    DogBoss98

    Joined:
    Feb 11, 2020
    Posts:
    3
    thanks for replying, in my scene I have a prefab that has already been inserted into the scene. It has a script which forms a graph out of the prefab. I also have another script named "Graph_insert" which is supposed to give the List to the function ShowGraph() in the first script named Window_Graph. Thanks again for your help.
     
  4. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    You need a reference to the instance of Window_Graph that is in your scene. This is not technically a "prefab". It's a clone of a prefab. The clone can be thought of like a car on an assembly line. So, if you want to change the radio on that car, you need to find that car and put in the new radio.

    The same logic applies here. You need to find that gameObject with your Window_Graph script and pass it the list however is appropriate for your script. In this case, your ShowGraph() method. There have been several forum responses as well as tutorials on how to access other scripts, the basic idea...

    Code (CSharp):
    1. public Window_Graph winGraph;
    2.  
    3. public void PopulateGraph()
    4. {
    5.    winGraph.ShowGraph(aList);
    6. }
     
    DogBoss98 likes this.
  5. DogBoss98

    DogBoss98

    Joined:
    Feb 11, 2020
    Posts:
    3
    Thank you so much, I've been stuck on this for ages. Thank you.