I am trying to get TestGrab to find the script PlatformStateMachine and execute the method LoadChaptersMenu, but the line below with the comment has the error: Object does not have a definition for LoadChaptersMenu, and no extension method accepting a first argument of object blah blah, common error. I dont know how I have failed to select or expose the method though.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
public void TestGrab ()
{
UnityEngine.Debug.Log("triggered");
object psm = Object.FindObjectOfType<PlatformStateMachine>();
psm.LoadChaptersMenu();// error shows up here
}
PlatformStateMachine.cs:
using System;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class PlatformStateMachine : MonoBehaviour
{
public static void LoadChaptersMenu()
{
UnityEngine.Debug.Log("executed");
}
}
Someone can probably find where this is answered somewhere else, but with my limited knowledge of the problem I was unable find such a solution in my searches. I cannot execute code in unity for debug if there's a syntactical error, Don't know what troubleshooting step to take other than ask on here.
Test.cs
using UnityEngine;
public class Test : MonoBehaviour
{
public void TestGrab()
{
Debug.Log("triggered");
var psm = FindObjectOfType<PlatformStateMachine>();
psm.LoadChaptersMenu();
}
}
PlatformStateMachine.cs
using UnityEngine;
public class PlatformStateMachine : MonoBehaviour
{
public void LoadChaptersMenu()
{
Debug.Log("executed");
}
}
In Test.cs you implicitly casted the PlatformStateMachine to an object, and object is the super class of everything and does not have the LoadChaptersMenu method.
Since you get an instance of PlatformStateMachine when you use FindObjectOfType, you don't want to use a static method, so I removed the static modifier in PlatformStateMachine.cs. If you want the method to be static, invoke it in a static way, like:
PlatformStateMachine.LoadChaptersMenu();
It would be ok to do a check after or before looking for the object. For example:
var psm = FindObjectOfType<PlatformStateMachine>();
if(psm == null)
throw new System.Exception("Object of type " + typeof(PlatformStateMachine) + " not found!");
psm.LoadChaptersMenu()
But I recommend making a public reference, to save from memory. Because FindObjectOfType eats up a lot of memory when called. Sorry for bad english!!!