- Home /
Using sliders to control X and Z of an object
I'm trying to control an objects X and Z using 2 sliders (1 for each value). It worked fine using the script for X, but when using the script for Z nothing happens. Both are applied to the object and both "AdjustWidth" and "AdjustHeight" are added to the slider value.
Code for X:
using UnityEngine;
using System.Collections;
public class Gulv_bredde : MonoBehaviour
{
// Use this for initialization
public float gulvBredde = 1f;
void Start()
{
}
public void AdjustWidth(float nyBredde)
{
gulvBredde = nyBredde;
}
// Update is called once per frame
void Update()
{
transform.localScale = new Vector3(1f+gulvBredde, 0.25f, 1f);
}
}
Code for Y:
using UnityEngine;
using System.Collections;
public class GulvLengde : MonoBehaviour
{
// Use this for initialization
public float gulvLengde = 1f;
void Start()
{
}
public void AdjustHeight(float nyLengde)
{
gulvLengde = nyLengde;
}
// Update is called once per frame
void Update()
{
transform.localScale = new Vector3(1f, 0.25f, 1f+gulvLengde);
}
}
Any help is appreciated!
Answer by AndreasLybo · Jul 16, 2016 at 03:13 PM
I changed the code to this and it now works :)
Z:
Vector3 scale = transform.localScale;
scale.z = gulvLengde;
transform.localScale = scale;
X:
Vector3 scale = transform.localScale;
scale.x = gulvBredde;
transform.localScale = scale;
Answer by wojtask12 · Jul 16, 2016 at 02:59 PM
Note 1: use English in your code, it'll make your life easier. trust me. Note 2: Your approach is really bad, you should avoid calling Update()
function if it's not necessary. Note 3: You're trying to do 2 things every frames:
transform.localScale = new Vector3(1f, 0.25f, 1f+gulvLengde);
and
transform.localScale = new Vector3(1f+gulvBredde, 0.25f, 1f);
First operation sets your object's scale to, let's say (1,0.25,1.53) (Z value dependent on slider value) Second operation takes this rescaled object and it rescales it again - in this point, it sets Z scale back to 1 - so the output scale is (1+sliderValue,0.25,1). You need to have it this way:
float xScale, zScale;
Transform objectToResize;
public void RescaleX(float sliderValue)
{
xScale = sliderValue;
ResizeObject();
}
public void RescaleZ(float sliderValue)
{
zScale= sliderValue;
ResizeObject();
}
void ResizeObject()
{
objectToResize.localScale = new Vector3(xScale, 0.25f, zScale);
}
Assign RescaleX
and RescaleZ
to your sliders, and it's done.
Your answer
Follow this Question
Related Questions
How can i check and fire an event when the user look at specific object ? 0 Answers
Adding callbacks/events to an instantiated prefab 2 Answers
How do I inherit certain varibles and functions from another script. 1 Answer
building error in my video project apk 0 Answers
Running scripts from editor 1 Answer