Unity 3D粒子碰撞功能开发代码报错问题排查求助
错误修复列表
你遇到的所有问题修改如下:
1. 解决CS1001、CS1003语法错误
错误出现在第56行OnCollisionEnter方法的参数定义,原代码错误写为:private void OnCollisionEnter(Collision collision other)
Collision是参数类型,后面只能跟一个自定义参数名,同时写collision和other两个标识符不符合C#语法,修改为private void OnCollisionEnter(Collision other)即可。
2. 修复其他逻辑/拼写错误
other.gameObject.CampareTag("Rock")拼写错误,正确方法名为CompareTagplayerAnim.SetInterger("DeathType_int", 1)拼写错误,正确Animator方法名为SetIntegerplayerAnim变量未初始化,需要在Start()方法中补充代码playerAnim = GetComponent<Animator>();,否则运行时会触发空引用异常OnGUIDepth changed属于Unity编辑器临时提示,不是代码错误,修改完代码重启编辑器即可消除
修正后完整代码
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController1 : MonoBehaviour { public float horizontalInput; public float speed = 10.0f; public float xRange = 100; private Animator playerAnim; public AudioClip crashSound; private AudioSource playerAudio; public GameObject projectilePrefab; public ParticleSystem explosionParticle; public bool isOnGround = true; public bool gameOver; // Start is called before the first frame update void Start() { playerAudio = GetComponent<AudioSource>(); playerAnim = GetComponent<Animator>(); } // Update is called once per frame void Update() { if (transform.position.x < -xRange) { transform.position = new Vector3(-xRange, transform.position.y, transform.position.z); } if (transform.position.x > xRange) { transform.position = new Vector3(xRange, transform.position.y, transform.position.z); } horizontalInput = Input.GetAxis("Horizontal"); transform.Translate(Vector3.right * horizontalInput * Time.deltaTime * speed); if (Input.GetKeyDown(KeyCode.Space)) { Instantiate(projectilePrefab, transform.position, transform.rotation); } } private void OnCollisionEnter(Collision other) { if (other.gameObject.CompareTag("Rock")) { isOnGround = true; } else if (other.gameObject.CompareTag("Star")) { Debug.Log("Game Over"); gameOver = true; playerAnim.SetBool("Death_b", true); playerAnim.SetInteger("DeathType_int", 1); explosionParticle.Play(); playerAudio.PlayOneShot(crashSound, 1.0f); } } }
内容的提问来源于stack exchange,提问作者Jazzmine McLeod
相关产品推荐
相关产品推荐

