在静态类中设置除null之外的材质

时间:2013-12-27 18:42:52

标签: c# unity3d

在静态类中,我有一个静态变量,其材质设置为null,然后通过另一段代码将其重写为其他值。唯一的问题是当比赛开始时球没有材料,它只是一个2d的粉红色圆圈。我已经尝试了多种方法将Ball材质设置为null以外的其他东西但没有效果。

以下是我在静态中的代码:

using UnityEngine;
using System.Collections;

static class ballmaterial 
{
    public static Material BallMaterial = null;
}

任何帮助将不胜感激,谢谢:)

1 个答案:

答案 0 :(得分:1)

你可以通过这种方式使用单例模式来避免使用static关键字(从代码中榨取生命):

using UnityEngine;
using System.Collections;

class ballmaterial 
{
    private static ballmaterial instance;
    private ballmaterial() {}

    public static ballmaterial Instance {
       get {
           if (instance == null) {
               instance = new ballmaterial();
           }
           return instance;
       }
    }

    public Material BallMaterial = null;
}

然后你应该可以从代码中的任何地方设置BallMaterial:

//in your gameobject component
public Material targetMaterial //the material you want to set it to (visible in inspector)
ballmaterial.Instance.BallMaterial = targetMaterial;

要在场景之间进行修改,您应该使用DontDestroyOnLoad函数:

//in your gameobject component
void Awake() {
    DontDestroyOnLoad (this);
}