Calling a function in a prefab from a function of another GameObject in C#,Calling a function in a prefab from a function in another GameObject in C#
Hi, I'm a Unity beginner and even though I found several similar questions to mine, none of the answers really helped so I'm asking my specific question:
I have a button that instatiates (as child) a prefab GameObject with a script attached.
I have another button (also child of the first button) that is then supposed to call a function from that prefab's script.
Here is the code that's on the child button:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class externactive : MonoBehaviour
{
public GameObject button;
public GameObject thing;
public move myScript;
public void Find ()
{
thing = button.transform.Find("Mixfigur(Clone)").gameObject;
myScript = thing.GetComponent<move>();
myScript.Activate();
}
}
The parent button is drag&dropped into the "button" slot in Unity interface. The prefab's script is called "move" and it has a function "Activate ()". Upon running this, the "thing" slot gets filled with the prefab correctly, but running its function does not work.
I tried the exact same code with a non-prefab game object and it works. The problem seems to be directly tied to it being a prefab. Here is the code for that second example, again on the button that wants to call a function (this time on a non-prefab GameObject):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class zwei : MonoBehaviour {
public GameObject target;
public ballscript ballFull;
public void Kicking ()
{
target = transform.Find("Ball").gameObject;
ballFull = target.GetComponent<ballscript>();
ballFull.Kick();
}
}
The "Ball" is a child of the button to make sure the same Find operation as in the first script has to find it during runtime. This code works just fine. I cannot see a difference. Does the problem have something to do with prefabs just being handled differently?
Your answer
![](https://koobas.hobune.stream/wayback/20220612202804im_/https://answers.unity.com/themes/thub/images/avi.jpg)