- Home /
Drag and drop reference not working?
I made a reference to a script and I was going to go ahead and drag the script into the slot, but it didn't let me do so. Turns out, nothing goes into that slot. Any help? Here's the script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tutorial : MonoBehaviour
{
public levelMenu levelMenu;
public void Start()
{
if(levelMenu.tutorialStart)
{
Debug.Log("tutorial");
}
}
}
Answer by kirbygc00 · Apr 11, 2020 at 08:30 PM
I would generally use a scriptable object. it's a great way to serialize data and supply it to scripts.
However to answer your specific question, try instantiating the script on some gameobject in the scene, then drag that into the Tutorial
's levelMenu
field.
Thank you very much! This has definitely helped, but what if the game object with the script is in a different scene, would it still be possible to do this? @kirbygc00
Yup! In cases where the game object is not readily available in the scene I generally grab the script reference through code. So I would do something like:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tutorial : $$anonymous$$onoBehaviour
{
public level$$anonymous$$enu level$$anonymous$$enu;
public void Start()
{
// on start this reference would be null, so we need to assign it
if (level$$anonymous$$enu == null)
// look through objects in scene to find one which contains the
// level$$anonymous$$enu component, then assign that component as the reference
level$$anonymous$$enu = FindObjectOfType<level$$anonymous$$enu>();
}
}
I don't believe it is possible to grab a script which isn't loaded into the current scene through this method. In case you do need this kind of behaviour, I would use the Resources.Load
method to dynamically load it in: https://docs.unity3d.com/ScriptReference/Resources.Load.html using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Tutorial : $$anonymous$$onoBehaviour
{
public level$$anonymous$$enu level$$anonymous$$enu;
public void Start()
{
// on start this reference would be null, so we need to assign it
if (level$$anonymous$$enu == null)
// grab the script from your "resources" folder, you may need to also instantiate a gameobject with the script loaded as a component... just wrap this call in an instantiate method.
level$$anonymous$$enu = Resources.Load<level$$anonymous$$enu>("path/to/object");
}
}