Unity3D展示必用的动态改变模型大小与方向。先在场景内放置一个cube,设置一个guiskin,并附上中文字体。将Code保存为js,赋给cube。
public var mySkin:GUISkin;
var windowRect = Rect (0, 20, 200 ,150);
var SliderScaleValue:float = 0.0;
var SliderXValue:float = 0.0;
var SliderYValue:float = 0.0;
var SliderZValue:float = 0.0;
var SliderWindowRect = Rect(80,200,200,150);
var mCube:GameObject;
var xRotation:float;
var yRotation:float;
var zRotation:float;
var wenzi : String;
function Start(){
mCube = GameObject.Find(“Cube”);
//print(mCube.transform.lossyScale + ” — ” + mCube.transform.localScale);
SliderScaleValue = mCube.transform.localScale.x;
}
function Update () {
}
function OnGUI () {
GUI.skin = mySkin;
SliderWindowRect = GUI.Window(1,SliderWindowRect,CreateWindow,wenzi);
}
function CreateWindow(windowID : int){
GUI.skin = mySkin;
GUI.Label(Rect(10,20,50,20),”缩放”);
SliderScaleValue = GUI.HorizontalSlider (Rect(60,25,120,20),SliderScaleValue,0,500);
//设置汽车的scale
mCube.transform.localScale = Vector3(SliderScaleValue,SliderScaleValue,SliderScaleValue);
GUI.Label(Rect(10,50,50,20),”旋转X”);
SliderXValue = GUI.HorizontalSlider (Rect(60,55,120,20),SliderXValue,0,360);
//设置汽车的xRotation
if(xRotation != SliderXValue){
mCube.transform.rotation = Quaternion.Euler(SliderXValue,yRotation,zRotation);
xRotation = SliderXValue;
}
GUI.Label(Rect(10,80,50,20),”旋转Y”);
SliderYValue = GUI.HorizontalSlider (Rect(60,85,120,20),SliderYValue,0,360);
//设置汽车的yRotation
if(yRotation != SliderYValue){
mCube.transform.rotation = Quaternion.Euler(xRotation,SliderYValue,zRotation);;
yRotation = SliderYValue;
}
GUI.Label(Rect(10,110,50,20),”旋转Z”);
SliderZValue = GUI.HorizontalSlider (Rect(60,115,120,20),SliderZValue,0,360);
//设置汽车的zRotation
if(zRotation != SliderZValue){
mCube.transform.rotation = Quaternion.Euler(xRotation,yRotation,SliderZValue);;
zRotation = SliderZValue;
}
GUI.DragWindow (Rect (0,0,10000,10000));
}
在Unity中,Cube1.transform.localScale.x = 0.5f 这行代码会报错,原因是 localScale 是一个 Vector3 类型的属性,而 Vector3 的属性(如 x, y, z)是只读的。
你不能直接对 localScale.x 进行赋值。
要修改物体的缩放,你需要先获取整个 localScale,然后修改它的某个分量,最后再将其赋值回去。
正确的写法如下:
```
Vector3 scale = Cube1.transform.localScale;
scale.x = 0.5f; // 修改x分量
Cube1.transform.localScale = scale; // 将修改后的值赋回去
```
或者直接new一个Vector3变量直接赋值,如:
```
Cube1.transform.localScale = new Vector3(0.5f, 0.5f, 0.5f);
Cube2.transform.localScale = new Vector3(0.5f, 0.5f, 0.5f);
```
这样就可以正确地改变物体的缩放了。
=new Vector3();