I'm working on this VR musical game, now I'm trying to make a slider value change the alpha parameter on a material with no luck. It doesn't give me any error, but the slider doesn't seem to affect the alpha value and when changing the public alpha parameter in the inspector, the sphere to which I attached the material doesn't change transparency at all. I have already tested the material, changing the alpha value directly from there and it works fine (material is set to transparent and everything).
I'm a noob so sorry if this is really simple!
Here's the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ColorChange : MonoBehaviour
{
public GameObject currentGameObject;
public float alpha = 0.5f;//half transparency
//Get current material
public Material currentMat;
public Slider slider;
// Start is called before the first frame update
void Start()
{
currentGameObject = gameObject;
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 ChangeAlphaOnValueChange(Slider slider)
{
ChangeAlpha(currentMat, slider.value / 250);
}
}
Don't know if it makes ay difference, but I'm using the slider so that I can control it though a trackpad, and then the slider can tell the value to the material. An issue I've got is that the trackpad is feeding the slider values from -1 to 1, when it would probably be better to have them 0 to 1. Any ideas for that? (for now I'm happy to just have it working with whatever numbers, but it would be nice if any of you guys could point me in the right direction for this too).
Thanks a lot for the help!
CodePudding user response:
You don't seem to be calling the ChangeAlphaOnValueChange
method anywhere within this script? If you don't relate the method in some way to one of Unity's event methods, it won't be called. It depends on what exactly you're trying to achieve, but you need to be making a call to ChangeAlphaOnValueChange
in at least one of Start
and Update
methods.
An issue I've got is that the trackpad is feeding the slider values from -1 to 1, when it would probably be better to have them 0 to 1. Any ideas for that?
Use math: say x
is the input from the trackpad, between -1 and 1. x 1
ranges from 0 to 2. (x 1) / 2
gives you a range between 0 and 1. When implementing this though, be wary of integer division, you want to be in control of the data type (float, etc.) throughout.
Edit: For the slider event, see Slider.onValueChanged
. Add a callback to it in your Start
method. Perhaps you've already tried attaching the method to the slider through the editor instead, but this is worth a shot.