Duplicate Question
I need to activate a function in another script from a script on a different game object
// The first script that accesses the functions when condition is met
public class scriptOne : MonoBehaviour
{
public GameObject genGameObject;
gen genScript;
void Start()
{
gen genScript = genGameObject.GetComponent<gen>();
}
void Update()
{
if (genScript.upFlag == true)
{
genScript.upSelected();
}
}
}
// The second script containing the functions
// and flags to be called or changed
public class gen : MonoBehaviour
{
public bool upFlag = false;
public void upSelected()
{
// The values within a class I wish to change being incremented here
}
}
I keep getting an error stating that genScript is never changed and in the example from years ago that I was using as reference (linked here: https://answers.unity.com/questions/550578/cant-understand-getcomponent-c.html), they don't even state the 'gen genScript' variable in the code but it works anyways. Without this, it doesn't work at all.
Hi @Alluma, the example you found shows how to do it if the two scripts are on the same object. then you can just use GetComponent without prefacing it with a reference to the object. So:
// 1.) this:
gen genScript; // at the top of your script
genScript = GetCompnent<gen>(); // inside some function
// 2. ) is different than this
public GameObject genGameObject; // at the top of your script
gen genScript;
genScript = genGameObject.GetComponent<gen>(); // inside some function
...
// Note do not declare genScript again by stating: 'gen genScript'
// inside your functions because you've already declared the variable.
// Declaring a variable in a function makes it local only to that function.
...
// example 1) assumes gen is on the same object as this script
// 2) looks for gen on the object referenced by the variable 'genGameObject'
Does that help?
Note also that you really should Capitalize the first letter of all Classes and Function identifiers to make your code easy for other people to follow, and easier for you to spot too. So declare the 'gen' class ins$$anonymous$$d as
public class Gen : $$anonymous$$onoBehaviour
// and
public class ScriptOne : $$anonymous$$onoBehaviour
You are declaring a local variable in the Start
method so the class variable is never set;
public class scriptOne : $$anonymous$$onoBehaviour
{
public GameObject genGameObject;
private gen genScript = null;
void Start()
{
genScript = genGameObject.GetComponent<gen>();
}
void Update()
{
if (genScript.upFlag == true)
{
genScript.upSelected();
}
}
}
FAQ :
Some reasons for getting a post rejected:
Posting about a specific compiling error or NullReferenceException: there is a myriad of these questions with answers already, have a look at those posts to get hints on what could possibly be your issue. Also, take a look at the Unity's support website and official C# documentation, many errors and how to solve them are described here