首页 > 解决方案 > C# 代码可在一个脚本中工作,但不能在另一个脚本中工作

问题描述

我目前正在学习 C#,因为我正在大学学习游戏设计课程。我目前正在实施一个系统:当时间达到 0 时,游戏暂停并结束。这有效:)。

但是,起初我尝试将代码实现到另一个脚本中 - 但不适用于该脚本。这让我很困惑。这是代码(有效):

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

public class Health : MonoBehaviour
{
    private Text TimeText;
    public float HealthTimer;
    public bool TimeIsRunning;
    public GameObject CanvasEnd;
  
    void Start()
    {
        
        TimeText = GameObject.Find("Timer").GetComponent<Text>();
        TimeIsRunning = true;

        CanvasEnd.SetActive(false);

    }


    void Update()
    {
        TimeText.text = HealthTimer.ToString("0");

        if (TimeIsRunning == true)
        {
            if (HealthTimer > 0)
            {
                HealthTimer -= 1 * Time.deltaTime;
            }

            else
            {
                Time.timeScale = 0;
                CanvasEnd.SetActive(true);
            }

            if(HealthTimer == 0)
            {
                TimeIsRunning = false;
                HealthTimer = 0;
            }

        }

此脚本直接附加到计时器。但是我不明白为什么当我将它实现到另一个脚本(已经控制其他游戏方面)时它不起作用。没有错误,一切都正确声明。

完全相同的代码被放入此脚本(无效更新)并且不起作用:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
 public GameObject Player;
    public GameObject PlayerTracker;
    public GameObject BlueBottle;
    public GameObject GreenBottle;
    public GameObject RedBottle;
    public GameObject ChestCanvas;
    public float Score;
  
    public float ChestScoreK = 0;
    private Text HT;
    private Text HC;
    private Text Port;
    private Text TimeText;
    
   
    float speed = 4;
    float rotSpeed = 80;
    float rot = 0f;
    float gravity = 8;
    // Variables counting Blue, Red and Green bottles
    public int BBCounter = 0;
    public int RBCounter = 0;
    public int GBCounter = 0;
    public int CCounter = 0;
    Vector3 moveDir = Vector3.zero;

    CharacterController controller;
    Animator anim;


   

    void Start()
    {
        controller = GetComponent<CharacterController>();
        anim = GetComponent<Animator>();
        ChestCanvas.SetActive(false);
        TimeText = GameObject.Find("Timer").GetComponent<Text>();
    }

    void Update()
    {

//Script was implemented here

       




        if (controller.isGrounded)
        {
            if (Input.GetKey(KeyCode.W))
            {
                anim.SetInteger("condition", 1);
                moveDir = new Vector3(0, 0, 1);
                moveDir *= speed;
                moveDir = transform.TransformDirection (moveDir);
            }
            if (Input.GetKeyUp(KeyCode.W))
            {
                anim.SetInteger("condition", 0);
                moveDir = new Vector3(0, 0, 0);
            }
        }
        rot += Input.GetAxis("Horizontal") * rotSpeed * Time.deltaTime;
        transform.eulerAngles = new Vector3(0, rot, 0);

        moveDir.y -= gravity * Time.deltaTime;
        controller.Move(moveDir * Time.deltaTime);

    }

    

    private void FixedUpdate()
    {
        PlayerTracker.transform.position = Player.transform.position;
       

    }



    private void OnTriggerEnter(Collider other)
    
        
    
    {
        if (other.gameObject.tag == "BlueBottle")
        {
            Debug.Log("BLUE");
            BBCounter = BBCounter + 1;
           

            GameObject MasterScriptBlue = GameObject.Find("GameMaster");
            MasterScriptBlue.GetComponent<GameMasterScript>();
            MasterScriptBlue.GetComponent<GameMasterScript>().BlueBottleCounter = BBCounter;
                                   
            
        }
        if (other.gameObject.tag == "RedBottle")
        {
            Debug.Log("RED");
            RBCounter = RBCounter + 1;
            GameObject MasterScriptRed = GameObject.Find("GameMaster");
            MasterScriptRed.GetComponent<GameMasterScript>();
            MasterScriptRed.GetComponent<GameMasterScript>().RedBottleCounter = RBCounter;

            

        }
        if (other.gameObject.tag == "GreenBottle")
        {
            Debug.Log("GREEN");
            GBCounter = GBCounter + 1;
            GameObject MasterScriptGreen = GameObject.Find("GameMaster");
            MasterScriptGreen.GetComponent<GameMasterScript>();
            MasterScriptGreen.GetComponent<GameMasterScript>().GreenBottleCounter = GBCounter;

            
        }

        if(other.gameObject.tag == "CityCollider")
        {

            GameObject HuntingCity = GameObject.Find("HC");
            Destroy(HuntingCity);

            ScoringSystem.theScore += 100;

            Destroy(other.gameObject);
            Debug.Log("Destroyed");

        }

        if(other.gameObject.tag == "TownCollider")
        {
            GameObject HuntingTown = GameObject.Find("HT");
            Destroy(HuntingTown);
            

            ScoringSystem.theScore += 100;

            Destroy(other.gameObject);
            Debug.Log("Destroyed");

            Debug.Log("Destroyed");
        }


        if(other.gameObject.tag == "PortCollider")
        {
            GameObject Port = GameObject.Find("Port");
            Destroy(Port);

            ScoringSystem.theScore += 100;

            Destroy(other.gameObject);
            Debug.Log("Destroyed");


        }

       if(other.gameObject.tag == "Chest")
        {

            Time.timeScale = 0;
            ChestCanvas.SetActive(true);

            ChestScoreK += 1;
            GameObject MasterScriptChest = GameObject.Find("GameMaster");
            MasterScriptChest.GetComponent<GameMasterScript>().ChestScore += ChestScoreK;
            Destroy(other.gameObject);
            GameObject HealthScript = GameObject.Find("Timer");
            HealthScript.GetComponent<Health>().TimeIsRunning = false;
        }

    }
}

接下来我可以尝试什么?

标签: c#visual-studiounity3d

解决方案


It's hard to understand the problem from your question, but if you are looking for potential problems in your script then it looks like you are comparing a float to zero here:

        if(HealthTimer == 0)
        {
            TimeIsRunning = false;
            HealthTimer = 0;
        }

So it is possible that HealthTimer is never exactly zero.

You probbaly want if (HealthTimer <= 0f) instead, or to move that block into the else block of your preceding if statement.

Other differences with the second script are:

  • the second script is not setting TimeIsRunning = true; in the Start() method,
  • other methods set Time.timeScale = 0; in the second script (not sure what impact this has, but may be relevant).

推荐阅读