- Home /
Access the content of another script
So... I am trying to go through some old unity tutorials, trying to make sort of a quiz game... The thing is ... they do it by getting scripts to communicate with one another. I tried going back, tried to see if the most basic code possible can communicate with each other.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScriptA : MonoBehaviour
{
public ScriptB other;
void Update() {
other.DoSomething();
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScriptB : MonoBehaviour
{
public void DoSomething()
{
Debug.Log("Hi there");
}
}
Well... The thing is... It did not work. I created 2 empty objects in an empty 2D scene, attached ScriptA to one, attached ScriptB to the other, dragged the empty object with ScriptB into the field of ScriptA ... And it displayed nothing. I am not sure what I did wrong. Please help.
That should be all you have to do. Can you add a start function to each of your scripts, and have a log in them. $$anonymous$$aybe your objects are not active?
Yeah it should work exactly how it is. When you look at object A in the inspector does it say object B in the script B field?
Are you sure you have enabled the log in the console? ($$anonymous$$ake sure the white bubble at the top right corner of the console is checked).
Try with another function
private GameObject cube;
public void DoSomething()
{
if( cube == null ) cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.position = Vector3.one * $$anonymous$$athf.Sin( Time.time ) ;
}
Answer by Cornelis-de-Jager · May 14, 2019 at 05:22 AM
The problem is that you dragged the Empty Object with ScriptB onto ScriptA. This will not work because ScriptA is expecting a ScriptB not a Object. Instead change the code as follow:
public class ScriptA {
public Transform ScriptBObj;
ScriptB other;
void Start () {
other = ScriptBObj.GetComponent<ScriptB>();
other.DoSomething();
}
}
If you really need to attach ScriptB to ScriptA directly - you need to have two inspectors, lock the one. Then drag the Script NOT the empty object, onto the field.
It's exaclty what you must not do.
Having public ScriptB other;
and dropping the gameObject holding the component ScriptB
is the correct way. Unity will automatically retrieve the reference to the component this way.