【问题标题】:Changing Tag of Collided Object Through Collision (Solved)通过碰撞更改碰撞对象的标记(已解决)
【发布时间】:2021-01-22 01:44:59
【问题描述】:

脚本已经过时,或者不是我需要的,但我找不到答案。

首先,我正在制作一个弹球风格的游戏,每当球碰到一块时,它就会改变颜色,但我有多个彩色球,我想将颜色锁定到位,以免有其他球更改它们(使游戏更容易一点)。我提供了一个脚本,对于一个简单的解决方案来说可能有点太复杂了。问题区域位于底部,带有 void FixedUpdate。

(我只是想换个标签):)

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

public class ColorBlue : MonoBehaviour
{
    public Material mat;
    public string ballTag;
    public bool reset = false;
    public bool found = false;

    

    public void OnCollisionEnter (Collision collisionInfo)
    {
        if (collisionInfo.collider.tag == "Ball" )
        {
             gameObject.GetComponent<MeshRenderer>().material.color = Color.blue;
             reset = true;
        }
    }

    public void FixedUpdate ()
    {
        if(reset)
        {
            GameObject.FindWithTag("Ball");
        }   found = true;
        
        if(found)
        {
            GameObject.FindWithTag("Ball").tag = "Untagged";
        }
    }
}

【问题讨论】:

    标签: c# unity3d tags collision


    【解决方案1】:

    而不是搜索带有 "Ball" 标签的游戏​​对象,您可能在场景中有多个标签。您可以在发生碰撞时直接更改标签。

    因为在 OnCollisionEnter 函数中你已经引用了游戏对象,你可以使用它来更改带有collisionInfo.gameObject.tag = "Untagged" 的标签。

    public void OnCollisionEnter (Collision collisionInfo) {
        if (collisionInfo.gameObject.CompareTag("Ball") && gameObject.CompareTag("Ball")) {
             // Get Mesh Renderer of the Colided Ball Component.
             var meshRenderer = collsionInfo.gameObject
                 .GetComponent<MeshRenderer>();
    
             // Change Color of collided ball to be the same as the ball it collided with.
             meshRenderer.material.color = gameObject
                .GetComponent<MeshRenderer>().material.color;
    
             // Set Tag to "Untagged" to make sure ball won't change color anymore
             colliderInfo.gameObject.tag = "Untagged";
        }
    }
    

    您还可以添加额外的代码来根据游戏对象的当前颜色更改颜色。另外,我建议您使用CompareTag(),它会检查您的场景中是否存在标签。

    如果您想获得碰撞的游戏对象,您可以使用collisionInfo.gameObject.tag 来做到这一点

    【讨论】:

    • 请注意,switch 中的 cmets 与行为不匹配 ;) 目前没有任何变化 ^^
    • 是的,我会编辑 cmets thx 的评论。
    • 我想你宁愿想要改变新的颜色..正如目前所说,你基本上是在做if(currentColor == blue){ currentColor = blue; } ;)
    • 所以,我想你们不明白是什么东西在变色,这完全是我的错,所以,哇哦雏菊。为了解决这个问题,改变颜色的是球正在碰撞的游戏对象,而不是球本身。为了更清楚地说明这一点,我试图让它与游戏对象发生碰撞,游戏对象改变颜色(我已经管理过),但我想在正确的颜色球时将颜色锁定到位击中正确的部分,我得出的结论是更改(或停用)Board Piece 上的标签会更容易......
    • ...因为标签是我允许球在碰撞后改变板件颜色的方式。故事的寓意,球击中棋子,棋子改变颜色,然后棋子标签变为阻止球碰撞颜色变化的标签。
    猜你喜欢
    • 2013-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-13
    相关资源
    最近更新 更多