如果要启用另一个对象的Sprite渲染器,我试图让if条件执行某项操作,但是它将无法正常工作。
这是我尝试的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PickUpReCharge : MonoBehaviour
{
public Animator anim;
public Animator animc;
public Animator anime;
public GameObject neon;
public GameObject chargesprite;
public AudioSource recharge;
public BoxCollider2D collision;
public SpriteRenderer blackout;
public AudioSource ambient;
public AudioSource music;
void Start()
{
anime.Play("Pickup", 0, 1f);
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
neon.GetComponent<PlayerMovement>().enabled = true;
chargesprite.GetComponent<SpriteRenderer>().enabled = false;
collision.GetComponent<BoxCollider2D>().enabled = false;
anim.SetBool("IsDead", false);
anim.Rebind();
animc.Rebind();
anime.Rebind();
recharge.Play();
Destroy(gameObject, 3.0f);
//activate blackout
blackout.GetComponent<SpriteRenderer>().enabled = false;
if (blackout.enabled)
{
ambient.Play();
music.Play();
}
}
}
}
公共停电具有禁用的Sprite渲染器。启用后,我希望最后的代码运行,但不会运行。
怎么了?
答案 0 :(得分:0)
Prodian问我是否尝试过gameobject.activeself,我想感谢你的建议。它完美地工作!我将引用类型更改为gameobject,并重新分配了它,并做了必要的修改,现在它就像一种魅力!
这是完整的新代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PickUpReCharge : MonoBehaviour
{
public Animator anim;
public Animator animc;
public Animator anime;
public GameObject neon;
public GameObject chargesprite;
public AudioSource recharge;
public BoxCollider2D collision;
public GameObject blackout;
public AudioSource ambient;
public AudioSource music;
void Start()
{
anime.Play("Pickup", 0, 1f);
}
void Update()
{
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
neon.GetComponent<PlayerMovement>().enabled = true;
chargesprite.GetComponent<SpriteRenderer>().enabled = false;
collision.GetComponent<BoxCollider2D>().enabled = false;
anim.SetBool("IsDead", false);
anim.Rebind();
animc.Rebind();
anime.Rebind();
recharge.Play();
Destroy(gameObject, 3.0f);
if (blackout.gameObject.activeSelf)
{
ambient.Play();
music.Play();
}
blackout.gameObject.SetActive(false);
}
}
}
编辑:还要注意一件事! if语句的位置非常重要。应当使该代码为false的代码之前。这意味着如果这样做的话,以前的代码会行得通,但是游戏对象代码对我来说要好得多,因为停电层是我必须一直处于关闭状态的一层。
基本上,我的旧代码有效!只需将if语句移到“ getcomponent ... enabled = false”之前,因为脚本是按顺序读取的。
答案 1 :(得分:0)
您的blackout
是SpriteRenderer
,因此对其调用GetComponent
是无效的。将其更改为:
blackout.enabled = true;
或使用:
anotherGameObject.GetComponent<SpriteRenderer>().enabled = true;
在GameObject上调用SetActive
不仅会禁用SpriteRenderer
组件!在某些情况下,这会更改您期望的行为。