【问题标题】:gameObject SetActive(false) is disabling all my child objectsgameObject SetActive(false) 正在禁用我的所有子对象
【发布时间】:2022-01-25 08:57:10
【问题描述】:

我有两个脚本,一个是父母,一个是孩子。如果使用 Input.("Fire1"),父脚本会提供 On Mouseover 方法供子级使用。然后它应该禁用鼠标悬停的对撞机并得分。但是我遇到了一个错误,如果我点击一个带有子脚本的预制对撞机,它将禁用所有预制游戏对象。我该如何解决这个问题,以便我的子脚本一次只允许禁用一个预制件?

父脚本

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

public class CollectableParent : MonoBehaviour
{
    
    protected GameManager gameManager;
    // Start is called before the first frame update
    void Awake()
    {
        gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
    }

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

    }

    public void OnMouseOver()
    {
        if (Input.GetButtonDown("Fire1"))
        {
            this.gameObject.SetActive(false);
            gameManager.UpdateScore(5);
        }
    }

 
    

    
    
}

子脚本

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

public class LevelOneJack : CollectableParent
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

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

        if (Input.GetButtonDown("Fire1"))
        {
            OnMouseOver();
           
        }
        
    }
   


}

【问题讨论】:

  • 请使用正确的标签!请注意,unityscript 是或更好的是曾经是一种 JavaScript 风格,类似于早期 Unity 版本中使用的自定义语言,现在早已弃用了!

标签: c# unity3d parent-child onmouseover disable


【解决方案1】:

所以我从子类“更新”方法中删除了子类 if 语句,而是在覆盖方法中调用 OnMoseOver 方法。效果很好,对象现在一次只能禁用一个。我认为问题是我在那里禁用了父脚本以禁用所有子脚本和对象。

我现在唯一的问题是,当我将鼠标悬停在一个对象上时,它会自动触发 UpdateScore 方法,即使有一个 If 语句在执行操作之前检查 Input 是否为真。 这是因为我的 if 语句语法错误

这是更新后的子脚本

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class LevelOneJack : CollectableParent
 {
     // Start is called before the first frame update
     void Start()
     {
 
     }
 
     // Update is called once per frame
     void Update()
     {
 
       
     }
 
         public override void OnMouseOver()
          {
         if(Input.GetButtonDown("Fire1"))
             base.OnMouseOver();
             gameManager.UpdateScore(5);
          }
 
      }

【讨论】:

    猜你喜欢
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-20
    相关资源
    最近更新 更多