Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
107 views
in Technique[技术] by (71.8m points)

c# - I need to change the transparency of the object through the slider

I have this script to change the transparency of the object, which is initially turned off, and when I click on the button that turns it on, its clone appears ... but when I turn on this object, I cannot change the transparency ... There are no errors in the unity, just not transparency changes ...

     public class ChangeOpacity : MonoBehaviour
       {
        public GameObject currentGameObject;
        private AsistantControll AsistantControllScript;
        public float alpha = 0.5f;//half transparency
                  //Get current material
     private Material currentMat;

     // Start is called before the first frame update
     void Start()
      {
         AsistantControllScript = FindObjectOfType<AsistantControll>();

       currentMat = currentGameObject.GetComponent<Renderer>().material;

    }

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

       }



        void ChangeAlpha(Material mat, float alphaVal)
     {
     Color oldColor = mat.color;
     Color newColor = new Color(oldColor.r, oldColor.g, oldColor.b, alphaVal);
    mat.SetColor("_Color", newColor);


     }

      public void ChangeAlphaOnValue(Slider slider)
     {
 ChangeAlpha(currentMat, slider.value);
 }




 }
question from:https://stackoverflow.com/questions/66052437/i-need-to-change-the-transparency-of-the-object-through-the-slider

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Some things are wrong in your code, or you haven't wrote all your code.
From where your ChangeAlphaValue method is called ? What slider is passed in parameter to it ?
You should add a serialize field of your slider in your script and reference it in the Inspector.

[SerializeField] private Slider m_slider = null;

void Start()
{
    ...
    m_slider.onValueChanged.AddListener(ChangeAlphaOnValue);
}

void OnDestroy()
{
    m_slider.onValueChanged.RemoveListener(ChangeAlphaOnValue);
}

public void ChangeAlphaOnValue(float value)
{
    ChangeAlpha(currentMat, value);
}

With that code, your ChangeAlphaOnValue is called whenever your slider change value (when you drag it at runtime or set it by code).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...