- Home /
unable to attach a script to a prefab
I have a prefab that I am using with a script attached to it. Here is the code:
using UnityEngine;
using System.Collections;
public class bagDetect : MonoBehaviour {
public GameObject okToShoot;
public bool canScore = true;
void Start () {
okToShoot.GetComponent<ID355> ().okToScore = true;
}
void Update () {
canScore = true;
}
}
the problem is i cannot seem to attach the reference to it. It will not let me drag and drop or assign the variable. This is the error i get when i run the game. Any ideas on what i am doing wrong?????
UnassignedReferenceException: The variable okToShoot of bagDetect has not been assigned. You probably need to assign the okToShoot variable of the bagDetect script in the inspector. UnityEngine.GameObject.GetComponent[ID355] () bagDetect.Start () (at Assets/bagDetect.cs:8)
You may need to edit the prefab instance, rather than the prefab itself.
The prefab's template can only contain references to assets or other objects internal to the prefab. You can only reference other scene objects once the prefab exists in a scene.
i think the issue is that the prefab is something that gets instantiated and there is none on the board until an event happens
so is it possible to assign a variable to prefab before it is instantiated?
The prefab itself can't hold references to scene objects, because there's no clear way to handle that if the prefab is dropped into another scene.
If you need a reference to something in the scene, I'd recommend the following:
Drop a copy of the prefab into your scene, somewhere out of the way.
Select the instance and disable it (checkbox in the inspector, next to the GameObject's name).
Set whatever value you need to set.
Your Instantiate
call can target the new instance that you just configured.
Answer by Meltdown · Jul 31, 2014 at 03:41 AM
What's happening is you're instantiating a prefab. This new prefab has no idea what okShoot is when its instantiated.
So what you need to do is something like this...
// Instantiate prefab and get its script
var instantiatedPrefab = GameObject.Instantiate(Resources.Load("PrefabName"));
var bagDetectObj = instantiatedPrefab.GetComponent<bagDetect>();
// Now set okShoot on the bagDetectScript on your instantiated prefab
bagDetectObj.okShoot = GameObject.Find("okShootGameObject");
How would you do this with UI elements? GameObject.Find wont work for me?
There is nothing special about UI elements. Why doesn't GameObject.Find work?