I could just add scriptA to gameObjectB in the inspector, to make it easy, but that defeats the purpose of my question.
scriptA is attached to gameObjectA.
scriptB is attached to gameObjectB
scriptA is attached to scriptB (scriptB has a ‘public scriptA scripta’ variable)
So now, through scriptB, scriptA is “sort of” attached to gameObjectB.
How can I access components in gameObjectB, in scriptA?
It’s not “GetComponent().ekfajskfjsaklf” because that searches gameObjectA.
Don’t tell me I have to create a variable in scriptA for gameObjectB because that also defeats the purpose T_T
Not 100% sure exactly what you are asking but basically. You have two gameobjects, each with their own unique scripts? And you want to access components on gameobject 2 with the script on gameobject 1?
To do that you would need to reference gameobject 2 from the gameobject 1 script. So like…
//JavaScript
//GameObject 1 Script
public var _go2 : GameObject;
function Start{
//For purpose of example let's assume GameObject2 has an AudioSource that we want to manipulate
var _audioSource = _go2.GetComponent(AudioSource);
//The local variable _audioSource will now be a reference to the AudioSource component on GameObject2
//If you want to access a script on GameObject 2 you could do something like this
var _go2_Script = _go2.GetComponent(NAMEOFSCRIPT);
// _go2_Script is now a local reference to GameObject 2's NAMEOFSCRIPT script
//To call a function or access a variable on NAMEOFSCRIPT, you would do something like this..
_go2_Script.TESTFUNCTION();
//You could also access the script and execute the test function like this
_go2.GetComponent(NAMEOFSCRIPT).TESTFUNCTION();
}
Hope this points you in the right direction! Sorry for my pseudocoded JavaScript!
no, ScriptA is referenced in ScriptB its not “attached” to ScriptB. unless ScriptA has some sort of reference to ScriptB it doesn’t know anything about ScriptB or the gameobject its attached to.
you either have to create a variable holding the reference or you pass in the reference through a function on ScriptA.
public class ScriptA:MonoBehaviour
{
public void myFunction(GameObject ScriptBGameobjgect)
{
....
}
}
public class ScriptB:MonoBehaviour
{
public ScriptA script;
private void Start()
{
script.myFunction(gameObject);
}
}
Ok that’s where I was confused, thanks.
I thought that I was “attaching” a scriptA instance to scriptB by dragging it in the inspector.
I guess I’ll create a private var in scriptA for scriptB, then using ‘get’ i’ll have scriptB reference itself to that instance of scriptA whenever it needs to.