0
\$\begingroup\$

So I have 3 scripts:

  • first for my player movementscript
  • second for my speed powerup speedscript
  • third for my obstacle box script i

I'm trying to get the component of box script in speed script, to get the function 'added' (which is in box script) into speed script but it keeps giving me nullreferenceexception error

Here are those scripts:

public class box : MonoBehaviour
{

    [SerializeField]
    GameObject effect;

    public int damage = 1;
    [SerializeField]
    float Speed =10f;
    [SerializeField]
    GameObject audioexplosion;


    void Update()
    {

        transform.Translate(Vector2.left * Speed* Time.deltaTime);

    }



    void  OnTriggerEnter2D(Collider2D col)
    {
        if(col.CompareTag("Player"))
        {
            Instantiate(audioexplosion, transform.position, Quaternion.identity);
            Instantiate(effect, transform.position, Quaternion.identity);

            movment tmp = col.GetComponent<movment>();

                tmp.health -= damage;
            Destroy(gameObject);
        }
    }
    public void added(float spd)
    {
        Speed += spd;
    }


}

And here is my speed script.

public class speedscript : MonoBehaviour
{
    [SerializeField]
    GameObject effect;
    [SerializeField]
    GameObject speedaudio;
    //[SerializeField]
   public float speed;
    public float add_v = 5;
    private float timeindue;
    //[SerializeField] 
 //  public box io;

    void Start()
    {

     //  io= GetComponent<box>();
       // Debug.Log(io);
    }


    void Update()
    {
        transform.Translate(Vector2.left * speed * Time.deltaTime);
    }


    void OnTriggerEnter2D(Collider2D sp)
    {
        if (sp.CompareTag("Player"))
        {
            Instantiate(speedaudio, transform.position, Quaternion.identity);
            Instantiate(effect, transform.position, Quaternion.identity);
            box io = GetComponent<box>();
                Debug.Log(io);
                io.added(add_v);

                Destroy(gameObject);
        }
    }
}
\$\endgroup\$
0
1
\$\begingroup\$

Are both the scripts on the same Gameobject? Because by using box io = GetComponent<box>(); statement you are getting the box.cs from the same gameobject where "speed.cs" is added. You can try box io = sp.GetComponent<box>();

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged .