修改其position的三个值
this.transform.position = new Vector3 (0.618f, 2.71828f, 3.14149f);
但有时候我们只想修改其中某一维的值
解决方案:
this.transform.position = new Vector3 (0.61803f, this.transform.position.y, this.transform.position.z);
在Unity中不能对transform.position.x/y/z直接赋值的原因探究
访问另一个脚本的变量,函数:
工程设置,一个简单的测试案例
通过Value脚本给物体添加另外两个脚本
Value.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Value : MonoBehaviour {
string poems = "Precious time, which cannot be recovered once lost.";
// Use this for initialization
void Start () {
this.gameObject.AddComponent<PrintStrs> ();
this.gameObject.AddComponent<deepThinking.NSprint> ();
PrintStrs.poemStrs = poems;
}
// Update is called once per frame
void Update () {
this.gameObject.GetComponent<PrintStrs> ().printPoem ();
this.gameObject.GetComponent<deepThinking.NSprint> ().printPome ();
}
}
PrintStrs.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PrintStrs : MonoBehaviour {
string GeYan = "Health is the thing that makes you feel that now is the best time of the year.";
public static string poemStrs = "Insincerity is always weakness; " +
"sincerity even in error is strength";
// Use this for initialization
void Start () {
print (poemStrs);
}
// Update is called once per frame
void Update () {
print (GeYan);
}
public void printPoem()
{
print (poemStrs);
}
}
NSprint.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace deepThinking {
public class NSprint : MonoBehaviour {
string LiBaiPoem = "古来圣贤皆寂寞,惟有饮者留其名。\n陈王昔时宴平乐,斗酒十千恣欢谑。";
// Use this for initialization
void Start () {
print ("人生得意须尽欢,莫使金樽空对月。");
}
// Update is called once per frame
void Update () {
}
public void printPome()
{
print (LiBaiPoem);
}
}
}
运行效果
通过脚本动态给物体添加一些属性各修改属性的值
给cube加 boxcollider和Rigidbody,并修改Is Kinematic属性不打勾。
enable是控制GameObject上的组件激活/关闭
Value.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Value : MonoBehaviour {
//GameObject NSprintScript = new GameObject ();
string poems = "Precious time, which cannot be recovered once lost.";
// Use this for initialization
void Start () {
this.gameObject.AddComponent<PrintStrs> ();
this.gameObject.AddComponent<deepThinking.NSprint> ();
deepThinking.NSprint NSprintScript = this.GetComponent<deepThinking.NSprint> ();
PrintStrs.poemStrs = poems;
this.gameObject.AddComponent<BoxCollider> ();
this.gameObject.GetComponent<BoxCollider> ().enabled = false;
this.gameObject.AddComponent<Rigidbody> ();
this.gameObject.GetComponent<Rigidbody> ().isKinematic = true;
this.gameObject.GetComponent<Rigidbody> ().useGravity = false;
this.gameObject.GetComponent<Rigidbody> ().mass = 7.18281828f;
}
// Update is called once per frame
void Update () {
this.gameObject.GetComponent<PrintStrs> ().enabled = false;
this.gameObject.GetComponent<deepThinking.NSprint> ().printPome ();
}
}