1

I know this question has been asked before, here and here.
But I still can't get variables from another script. I don't know what I'm doing wrong.
*(I'm really new to programming in general so I might have missed something glaringly obvious)

I keep on getting the error: The name 'points' does not exist in the current context

The slimespawner script is on the Canvas.

Sorry if the question is too simple.

here's the script I'm trying to access:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class slimespawner : MonoBehaviour
{
    public int points;
    public Text score;
    public float xx;
    public float yy;

    void Start()
    {
        points = 0;
        xx = Random.Range(-32f, 32f);
        yy = Random.Range(-18.5f, 18.5f);
    }

    void Update()
    {
        score.text = "Score: " + points.ToString();
    }
}

And here's the script that's trying to use the points variable.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class slimecontroller : MonoBehaviour
{
    private float movespeed = 0.1f;
    public slimespawner slisp;

    void Start()
    {
        slisp = GameObject.Find("Canvas").GetComponent<slimespawner>();
    }
    void Update()
    {
        points += 1;
    }
}
derHugo
  • 83,094
  • 9
  • 75
  • 115
  • have you tried with `base.points`?? – Prasad Telkikar Mar 20 '19 at 12:19
  • he means `slisp.points`. Note that if you reference this in the Inspector properly you don't need the whole `GameObject.Find("Canvas").GetComponent();` – derHugo Mar 20 '19 at 12:19
  • 1
    Possible duplicate of [How to access another class using C#(in unity3d)?](https://stackoverflow.com/questions/9822155/how-to-access-another-class-using-cin-unity3d) – derHugo Mar 20 '19 at 12:21

2 Answers2

1

Access the property with slisp.points += 1;

Aars93
  • 379
  • 4
  • 10
1

Your code should look as this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class slimecontroller : MonoBehaviour
{
    private float movespeed = 0.1f;
    public slimespawner slisp;

    void Start()
    {
        slisp = GameObject.Find("Canvas").GetComponent<slimespawner>();
    }
    void Update()
    {
        slisp.points += 1;
    }
}
Berme
  • 347
  • 1
  • 8
  • 1
    Note that if you reference this in the Inspector properly (since it is pubic anyway) you don't need the whole `GameObject.Find("Canvas").GetComponent();` – derHugo Mar 20 '19 at 12:21