[英]Ladder climbing function in C# script for Unity won't allow the character to come off the ladder
[英]C# Unity Script Won't Work
我是C#和Unity的新手,我從視頻中學習有關內容,並制作了一個腳本,該腳本會不斷記錄以管理一個使每次記錄翻倍的數字
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour {
// Use this for initialization
void Start () {
int Example;
Example = 1;
}
// Update is called once per frame
void Update () {
Example = Example * 2;
Debug.Log(Example);
}
}
我從邏輯上考慮
// Use this for initialization
void Start ()
首先,它只會運行一次,所以我在那里創建並設置了一個變量
int Example;
Example = 1;
然后使用更新每一幀的
// Update is called once per frame
void Update ()
翻倍
Example = Example * 2;
Debug.Log(Example);
但是,當我將其應用於對象並單擊播放時,它會顯示“必須先修復所有編譯器錯誤,然后才能進入播放模式”,並且在錯誤日志中顯示1警告和2錯誤:
警告:Assets / Example.cs(9,13):警告CS0219:已分配變量“示例”,但從不使用其值
錯誤:Assets / Example.cs(15,19):錯誤CS0119:表達式表示type', where a
應有變量', value' or
方法組'
錯誤:Assets / Example.cs(16,19):錯誤CS0119:表達式表示type', where a
應有變量', value' or
方法組'
我覺得這與系統沒有將“ Example”識別為存在的變量有關,因為我之前已經定義了它,所以我沒有得到
這可能是一個非常糟糕的錯誤,但是我仍然必須從錯誤中學習。
我的猜測是您的變量Example
不在正確的范圍內,因此您的update方法不知道它的存在。 嘗試這個:
public class Example : MonoBehaviour {
int example; //We declare it outside of the method so it is in the correct scope
// Use this for initialization
void Start () {
example = 1;
}
// Update is called once per frame
void Update () {
example = example * 2;
Debug.Log(example);
}
}
編輯:正如@Jon所指出的,您的變量名與您的類名相同,這會使編譯器感到困惑。 使用其他名稱。 對於這個例子,我只是把它變成小寫的example
您需要閱讀一些基本的C#
書籍並研究變量范圍。 C#
關心大小寫,因此您將int與類一樣調用,並且編譯器不知道在這種情況下該怎么做。
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour {
public int example;
// Use this for initialization
void Start()
{
example = 1;
}
// Update is called once per frame
void Update()
{
example = example * 2;
Debug.Log(example);
}
}
Unity網頁上有很多教程,它們的運行速度非常快,但是暫停和倒帶以及與之一起編寫代碼應該可以為您提供幫助。 https://unity3d.com/learn/tutorials/projects/roll-ball-tutorial
該錯誤是因為您有一個與類同名的變量。 將“ int示例”更改為其他內容。
這里有一些技巧(請看注釋行)
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour { // <---- Class name is capitalized so dont use same capitalization for "example" inside of class
int example; // <----- Put example here so it exists throughout the whole class
// Use this for initialization
void Start () {
example = 1; // <---- initialization
}
// Update is called once per frame
void Update () {
Debug.Log(example *= 2); // <------- Code shortening FTW
}
}
您的“示例”成員超出范圍。 就像威爾指出的那樣,成員與您的班級同名。 見下文
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour {
int myExample;
// Use this for initialization
void Start () {
myExample = 1;
}
// Update is called once per frame
void Update () {
myExample = myExample * 2;
Debug.Log(myExample);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.