**已关闭。**此问题为not reproducible or was caused by typos。目前不接受答案。
这个问题是由一个打字错误或一个无法再重现的问题引起的。虽然类似的问题在这里可能是on-topic,但这个问题的解决方式不太可能帮助未来的读者。
6天前关闭。
Improve this question
我遇到了标题错误代码,但不知道我是否遗漏了分号、大括号等。有人知道是什么导致了这个问题吗?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FBChatSim : MonoBehaviour{
// Initialise hashmaps and objects
// 2 hashmaps takes option as key and response overlay image path as value
Dictionary<string, string> imgDict=
new Dictionary<string, string>{
{"Option1", "chats/answer1.png"},
{"Option2", "chats/answer2.png"},
{"Option3", "chats/answer3.png"},
{"Option4", "chats/answer4.png"}
};
Dictionary<string, string> qnsDict=
new Dictionary<string, string>{
{"Option1", "chats/question1.png"},
{"Option2", "chats/question2.png"},
{"Option3", "chats/question3.png"},
{"Option4", "chats/question4.png"}
};
// 2 objects to store the image paths
public GameObject cube_qns;
public GameObject cube_reply;
// Initialise objects
cube_qns=GameObject.Find("Cube_Qns");
cube_reply=GameObject.Find("Cube_Reply");
// Declare helper functions
// ---- LoadPNG() | This function reads png files from the Resources folder as texture
public static Texture2D LoadPNG(string filePath){
Texture2D tex = null;
byte[] fileData;
if (File.Exists(filePath)){
fileData = File.ReadAllBytes(filePath);
tex = new Texture2D(2, 2);
tex.LoadImage(fileData); //..this will auto-resize the texture dimensions.
}
return tex;
}
// ---- ReplaceMyImages() | This function takes collided object as input and overlays image on it
// depending on which box is hit, image is assigned depending on imgDict and qnsDict
// replace text in chat bubble
// set chat bubble to visible
public void ReplaceMyImages(GameObject collidedObject){
private string obj_name=collidedObject.name;
cube_reply.GetComponent<Renderer>().material.mainTexture = LoadPNG(imgDict[obj_name]);
cube_qns.GetComponent<Renderer>().material.mainTexture = LoadPNG(qnsDict[obj_name]);
cube_qns.SetActive(true);
cube_reply.SetActive(true);
}
// Start is called before the first frame update
void Start(){
// set the chat bubbles to invisible
cube_qns.SetActive(false);
cube_reply.SetActive(false);
}
// Update is called once per frame
void Update(){
// ray cast and hit box
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
// invoke OverlayImage function if cube is hit
if (Physics.Raycast(ray, out hit) && Input.GetMouseButton(0)){
Debug.Log( "collide (name) : " + hit.collider.name);
ReplaceMyImages(hit.collider.gameObject);
}
}
}
我试着注解掉代码的某些部分,看看是哪个部分导致了这个问题,但是似乎没有一个部分会影响错误。我还通过逐个折叠括号来检查它们。
1条答案
按热度按时间fnvucqvd1#
这些行的位置不合适:
你不能随便给变量赋值。这些行需要在一个方法中,比如一个构造函数中。否则,你需要把赋值语句和变量的声明合并起来:
编辑:
我不使用Unity,所以我不知道Unity的具体细节,但是根据下面的评论,在声明这些变量的地方初始化它们似乎是不安全的。这意味着你需要接受我最初的建议,把赋值移到一个方法中,听起来
Start
是合适的方法: