- Home /
How can I call a method from another script?
Hi all, I read lots of similar question on unity community but I can't resolve my problem. I have 2 scripts. LeftShoulder.cs that has a method: prova(). From MainGUI.cs I want call the method prova(). But Unity return me this error: object reference not set to an instance of an object .
This is my code.
using UnityEngine;
using System.Collections;
public class LeftShoulder : MonoBehaviour {
public Transform from;
public Transform to;
public float speed = 100.0F;
public Component[] allcomponent;
// Use this for initialization
void Start () {
allcomponent=gameObject.GetComponents(typeof(Component));
// for(int i=0;i<allcomponent.Length;i++){
// Debug.Log(allcomponent[i]);
// }
}
// Update is called once per frame
void Update () {
// transform.Rotate (1f, 0f, 0f);
// ruota ();
// transform.rotation = Quaternion.Slerp(from.rotation, to.rotation, Time.time * speed);
}
public void ruota(int control){
if (control==1) {
transform.Rotate (Vector3.right * Time.deltaTime * 10);
}
}
}
and MainGUI.cs
using UnityEngine;
using System.Collections;
public class MainGUI : MonoBehaviour {
public Component spallasx;
public LeftShoulder spalla;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnGUI () {
GUI.BeginGroup(new Rect(0,0,120,120));
GUI.Box (new Rect (0,0,120,120), "Menu");
int a = 0;
if (GUI.Button (new Rect (10, 20, 100, 30), "primo bottone")) {
// spallasx = gameObject.GetComponent("LeftShoulder");
// Debug.Log("a");
a = 1;
spalla.ruota(a);
}
GUI.EndGroup ();
}
}
Answer by smoggach · Aug 19, 2014 at 03:50 PM
You have to drag the gameobject with the LeftShoulder script onto the MainGUI's spalla property in the inspector.
Answer by Pecek · Aug 19, 2014 at 03:49 PM
Use the search box please, this is probably the most common question here.
http://unity3d.com/search?refinement=answers&gq=access%20another%20script
Answer by DVFrance · Aug 19, 2014 at 04:36 PM
try something like this :
private GuiGame guiGameScript;
private GameObject guiGameObject;
void Awake()
{
guiGameObject = GameObject.Find ("GuiGameObject");
guiGameScript = guiGameObject.GetComponent<GuiGame>();
}
void Crash()
{
guiGameScript.CrashCounter();
}
here GuiGame is the name of the script I like to call. Once your script is found you could execute any of the public void you have in :
public class GuiGame : MonoBehaviour {
public void CrashCounter()
{
do your things !!!
}
}