- Home /
The question is answered, right answer was accepted
Acessing a Script Instance from Another Object
I have this script:
using UnityEngine;
using System.Collections;
public class Menu_Options : MonoBehaviour
{
//Vars
public Material GUI_N;
public Material GUI_O;
public static bool Active = false;
public Transform Menu;
public GameObject Cam;
//Functions
void OnMouseEnter()
{
renderer.material = GUI_O;
Active = true;
}
void OnMouseExit()
{
renderer.material = GUI_N;
Active = false;
}
void Update()
{
if(Active)
{
if(Input.GetMouseButtonUp(0))
{
Options();
Debug.Log("Options");
}
}
}
void Options()
{
var s = Cam.GetComponent<SmoothCam>();
s.Instance._SetTarget(Menu);
}
}
But i get this error:
Assets/Scripts/Menu_Options.cs(37,19): error CS0176: Static member `SmoothCam.Instance' cannot be accessed with an instance reference, qualify it with a type name instead
This is how the other script is set up:
using UnityEngine;
using System.Collections;
public class SmoothCam : MonoBehaviour {
public static SmoothCam Instance;
void Awake()
{
Instance = this;
}
public void _SetTarget(Transform t)
{
target = t;
}
---The rest is not important---
What does "qualify it with a type name" mean, and how can i fix or work around this?
Answer by Kmulla · Apr 18, 2012 at 08:35 PM
Try something like this:
public class Menu_Options : MonoBehaviour {
private SmoothCam SmoothCamScript;
void Awake() {
SmoothCamScript = Cam.GetComponent<SmoothCam>();
}
...
SmoothCamScript._SetTarget(Menu);
I've never tried anything with an 'instance' in the other script, but this method usually works for me :)
yay, that works perfect, i usually use instance when it's on the same object. thank you so much for your help.
The "Instance" thing you used was actually called singleton pattern (though, its more of a hybrid, but similar to it). Actually this pattern should be used used only in certain situations (Game$$anonymous$$anager for example).
Static variables are accessed via $$anonymous$$yClass.myStaticVariable
w/o needing an instance of the script
Answer by Lttldude · Apr 18, 2012 at 08:30 PM
I think
var s = Cam.GetComponent<SmoothCam>();
should become
SmoothCam s = Cam.GetComponent<SmoothCam>();
because it defines the type s is.
Then if you want to run some function or get some variable off of that script use it like this
s._SetTarget(transform);
Hope this helps.
i'm trying to run the _SetTarget function located in the SmoothCam script from within the $$anonymous$$enu_Options script. that didn't work.
Answer by Tseng · Apr 18, 2012 at 08:45 PM
Your "Instance" variable is static, you don't need to obtain an instance to access it
void Options() {
var s = Cam.GetComponent<SmoothCam>();
s.Instance._SetTarget(Menu);
}
Just do
SmoothCam.Instance._SetTarget(Menu);