How can I assign gameObject from code using C #

I am working on a random coin generator. I have included the following code:

timer -= Time.deltaTime;

if (timer <= 0)
{

    Vector3 position = new Vector3(Random.Range(11f, 14f), Random.Range(-0.7f, 4.5f), 0);
    Instantiate(coins, position, transform.rotation);
    timer = delayTimer;
}

and I add a collision to select a coin and make a text with an estimate:

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

public class Collisions : MonoBehaviour {
    public  Text scoreText;
    private float score;
    // Use this for initialization
    void Start () {
    }

    // Update is called once per frame
    void Update () {

        scoreText.text = "Score : " + score;



    }

    private void OnCollisionEnter2D(Collision2D col)
    {
        if (col.gameObject.tag == "Player")
        {
            Destroy(gameObject);
            scoreText.text = "Score : " + score;
            score++;

        }
    }

}

so now, when I need to add text to the collection, I can’t and if I somehow assign the text to the collection, it will not count any grade

enter image description here

+4
source share
1 answer

You need a script or compilation to learn about a specific object in the scene. is not it?

Whenever you find yourself in this situation, you should reconsider your approach. Keep in mind:

  • . . .

  • .

  • ( ) ( prefab prefab prefab )

:

, prefab

?

.

? . , . GameController GuiController UserProfileController ..

GuiController:

public class GuiController : MonoBehaviour
{
    //singleton setup
    static GuiController instance;
    void Awake() { instance = this; }

    //now it ready for static calls

    public UnityEngine.UI.Text MyText;

    //static method which you can call from anywhere
    public static void SetMyText(string txt) { instance.MyText.text = txt; }
}

( ). script . My Text. script GuiController.SetMyText("Score : " + score)

script .

score, Collisions, 0 , script. , score Collisions, , , , . , Collisions, GameController script .

singleton:

public class GameController : MonoBehaviour
{
    static GameController instance;
    void Awake() { instance = this; }

    float score;
    public static float Score { get { return instance.score; } set { instance.score = value; } }
}

script , score++ GameController.Score++;

+4

Source: https://habr.com/ru/post/1663414/


All Articles