- Home /
Why can't I drag text into public text in the inspector when instantiated?
I am writing my game so that I have a spawner that instantiates an invisible cube with a collider on it that adds 1 point to a text shown above:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GiveScore : MonoBehaviour
{
float playerScore = 0;
private Text gameScoreText;
public void Start()
{
gameScoreText.text = playerScore.ToString();
}
// Use this for initialization
void OnCollisionEnter2D()
{
playerScore += 01;
}
}
the problem is, when i instantiate the object with the script on it, the text object that is connected to the public text disappears and it won't let me add it back in. Could I please have some help with my mistake?
Answer by melsy · Feb 01, 2018 at 03:50 PM
It's because you can't hold a scene object in a prefab. Instead add a class on a game object that holds the text then reference that object in the GiveScore class Make a new class called Score Manager add a private int called score and make a public method called AddScore(int scoreToAdd). In this method increment the player score with score += scoreToAdd;.
Now on collision enter reference this class and call the AddScore(1) method