【问题标题】:Unity: Set alpha via code [duplicate]Unity:通过代码设置 alpha [重复]
【发布时间】:2018-01-15 08:58:04
【问题描述】:

我正在开发一个安卓游戏,我想在敌人产生时淡入淡出,敌人使用标准(镜面着色器),渲染模式设置为淡入淡出,预制件在反照率中具有 0 alpha。为此我使用以下代码

敌人淡入

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

public class EnemySetAlpha : MonoBehaviour {

    public Color enemyMesh;
    public float fadetime = 255;

    // Use this for initialization
    void Start () {

        enemyMesh = GetComponent<SkinnedMeshRenderer> ().material.color;
    }

    // Update is called once per frame
    void Update () {
            fadeIn (fadetime);
    }

    void fadeIn(float time)
    {
        enemyMesh = new Color (1, 1, 1, 0 + (fadetime*Time.deltaTime));
    }
}

我面临的问题是脚本增加 alpha 但反照率 alpha 仍然为 0 的敌人,因此不会在敌人中消失。

【问题讨论】:

  • 试一试:enemyMesh = GetComponent&lt;SkinnedMeshRenderer&gt; ().material; enemyMesh.SetColor(...);

标签: c# unity3d


【解决方案1】:

因为Color 是结构体(值类型),而不是类(引用类型),所以更改您的私有颜色enemyMesh 不会更改材质的颜色。 enemyMesh = GetComponent&lt;SkinnedMeshRenderer&gt; ().material.color; 制作材料颜色的副本。一个全新的实体。

你必须引用材料(这是一个引用类型)并改变它的颜色:

public class EnemySetAlpha : MonoBehaviour {

    public Material enemyMaterial;
    public float fadeSpeed = 0.1f;
    // Value used to know when the enemy has been spawned
    private float spawnTime ;

    // Use this for initialization
    void Start () {
        // Because `Material` is a class,
        // The following line does not create a copy of the material
        // But creates a reference (points to) the material of the renderer
        enemyMaterial = GetComponent<SkinnedMeshRenderer> ().material;
        spawnTime = Time.time ;
    }

    // Update is called once per frame
    void Update () {
            // Set the alpha according to the current time and the time the object has spawned
            SetAlpha( (Time.time - spawnTime) * fadeSpeed );
    }

    void SetAlpha(float alpha)
    {
        // Here you assign a color to the referenced material,
        // changing the color of your renderer
        Color color = enemyMaterial.color;
        color.a = Mathf.Clamp( alpha, 0, 1 );
        enemyMaterial.color = color;
    }
}

【讨论】:

  • 谢谢你这行得通,但是如何逐渐增加淡化时间来将 alpha 设置为 1,你能在你的答案中显示它吗?
  • 我已经更新了我的答案,以展示如何随着时间的推移更改 alpha 值。
  • 这不会按预期工作,因为Time.time 返回游戏运行的总时间。所以基本上,只要游戏运行超过 10 秒,这将设置大于 1 的 alpha 颜色...
  • @m.rogalski : 一个简单的 Clamp,问题就解决了 ;)
  • @Hellium 不,不是。假设 OP 会在游戏启动 1 分钟后生成敌人。使用你的代码敌人会产生完全褪色的、不透明的。它不会逐渐消失。
【解决方案2】:

加载对象后,您必须通过添加另一个“步长”值来修改(不仅仅是替换)alpha 值。

基本上,你需要的是这段代码:

void setAlpha()
{
    Color c = material.color;
    float current = c.a;
    current = Mathf.Min(current + fadetime * Time.deltaTime, 1.0f);
    c.a = current;
    material.color = c;
}

然后在您的Update 电话中,您只需进行一项简单的检查:

if(material.color.a < 1.0f)
{
    setAlpha();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    • 2010-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多