Ошибка компиляции Unity скрипта
Erstellt am: 16. Oktober 2024
Beantwortet mit O1 Preview von Chat01
Erstellt am: 16. Oktober 2024
Beantwortet mit O1 Preview von Chat01
почему когда я загидаваю на объект этот скрипт
/*
MESSAGE FROM CREATOR: This script was coded by Mena. You can use it in your games either these are commercial or
personal projects. You can even add or remove functions as you wish. However, you cannot sell copies of this
script by itself, since it is originally distributed as a free product.
I wish you the best for your project. Good luck!
P.S: If you need more cars, you can check my other vehicle assets on the Unity Asset Store, perhaps you could find
something useful for your game. Best regards, Mena.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PrometeoTruckController : MonoBehaviour
{
text//CAR SETUP [Space(20)] //[Header("CAR SETUP")] [Space(10)] [Range(20, 190)] public int maxSpeed = 90; //Максимальная скорость грузовика в км/ч. [Range(10, 120)] public int maxReverseSpeed = 45; //Максимальная скорость заднего хода в км/ч. [Range(1, 10)] public int accelerationMultiplier = 2; // Множитель ускорения. [Space(10)] [Range(10, 45)] public int maxSteeringAngle = 27; // Максимальный угол поворота колес. [Range(0.1f, 1f)] public float steeringSpeed = 0.5f; // Скорость поворота рулевого колеса. [Space(10)] [Range(100, 600)] public int brakeForce = 350; // Сила торможения. [Range(1, 10)] public int decelerationMultiplier = 2; // Множитель замедления. [Range(1, 10)] public int handbrakeDriftMultiplier = 5; // Множитель дрифта ручного тормоза. [Space(10)] public Vector3 bodyMassCenter; // Центр масс грузовика. //WHEELS //[Header("WHEELS")] public GameObject frontLeftMesh; public WheelCollider frontLeftCollider; [Space(10)] public GameObject frontRightMesh; public WheelCollider frontRightCollider; [Space(10)] public GameObject middleLeftMesh; public WheelCollider middleLeftCollider; [Space(10)] public GameObject middleRightMesh; public WheelCollider middleRightCollider; [Space(10)] public GameObject rearLeftMesh; public WheelCollider rearLeftCollider; [Space(10)] public GameObject rearRightMesh; public WheelCollider rearRightCollider; //PARTICLE SYSTEMS [Space(20)] //[Header("EFFECTS")] [Space(10)] public bool useEffects = false; public ParticleSystem RLWParticleSystem; public ParticleSystem RRWParticleSystem; public ParticleSystem MLWParticleSystem; public ParticleSystem MRWParticleSystem; [Space(10)] public TrailRenderer RLWTireSkid; public TrailRenderer RRWTireSkid; public TrailRenderer MLWTireSkid; public TrailRenderer MRWTireSkid; //SPEED TEXT (UI) [Space(20)] //[Header("UI")] [Space(10)] public bool useUI = false; public Text carSpeedText; //SOUNDS [Space(20)] //[Header("Sounds")] [Space(10)] public bool useSounds = false; public AudioSource carEngineSound; public AudioSource tireScreechSound; float initialCarEngineSoundPitch; //CONTROLS [Space(20)] //[Header("CONTROLS")] [Space(10)] public bool useTouchControls = false; public GameObject throttleButton; PrometeoTouchInput throttlePTI; public GameObject reverseButton; PrometeoTouchInput reversePTI; public GameObject turnRightButton; PrometeoTouchInput turnRightPTI; public GameObject turnLeftButton; PrometeoTouchInput turnLeftPTI; public GameObject handbrakeButton; PrometeoTouchInput handbrakePTI; //CAR DATA [HideInInspector] public float carSpeed; [HideInInspector] public bool isDrifting; [HideInInspector] public bool isTractionLocked; //PRIVATE VARIABLES Rigidbody carRigidbody; float steeringAxis; float throttleAxis; float driftingAxis; float localVelocityZ; float localVelocityX; bool deceleratingCar; bool touchControlsSetup = false; WheelFrictionCurve FLwheelFriction; float FLWextremumSlip; WheelFrictionCurve FRwheelFriction; float FRWextremumSlip; WheelFrictionCurve MLwheelFriction; float MLWextremumSlip; WheelFrictionCurve MRwheelFriction; float MRWextremumSlip; WheelFrictionCurve RLwheelFriction; float RLWextremumSlip; WheelFrictionCurve RRwheelFriction; float RRWextremumSlip; void Start() { carRigidbody = gameObject.GetComponent<Rigidbody>(); carRigidbody.centerOfMass = bodyMassCenter; FLwheelFriction = new WheelFrictionCurve(); FLwheelFriction.extremumSlip = frontLeftCollider.sidewaysFriction.extremumSlip; FLWextremumSlip = frontLeftCollider.sidewaysFriction.extremumSlip; FLwheelFriction.extremumValue = frontLeftCollider.sidewaysFriction.extremumValue; FLwheelFriction.asymptoteSlip = frontLeftCollider.sidewaysFriction.asymptoteSlip; FLwheelFriction.asymptoteValue = frontLeftCollider.sidewaysFriction.asymptoteValue; FLwheelFriction.stiffness = frontLeftCollider.sidewaysFriction.stiffness; FRwheelFriction = new WheelFrictionCurve(); FRwheelFriction.extremumSlip = frontRightCollider.sidewaysFriction.extremumSlip; FRWextremumSlip = frontRightCollider.sidewaysFriction.extremumSlip; FRwheelFriction.extremumValue = frontRightCollider.sidewaysFriction.extremumValue; FRwheelFriction.asymptoteSlip = frontRightCollider.sidewaysFriction.asymptoteSlip; FRwheelFriction.asymptoteValue = frontRightCollider.sidewaysFriction.asymptoteValue; FRwheelFriction.stiffness = frontRightCollider.sidewaysFriction.stiffness; MLwheelFriction = new WheelFrictionCurve(); MLwheelFriction.extremumSlip = middleLeftCollider.sidewaysFriction.extremumSlip; MLWextremumSlip = middleLeftCollider.sidewaysFriction.extremumSlip; MLwheelFriction.extremumValue = middleLeftCollider.sidewaysFriction.extremumValue; MLwheelFriction.asymptoteSlip = middleLeftCollider.sidewaysFriction.asymptoteSlip; MLwheelFriction.asymptoteValue = middleLeftCollider.sidewaysFriction.asymptoteValue; MLwheelFriction.stiffness = middleLeftCollider.sidewaysFriction.stiffness; MRwheelFriction = new WheelFrictionCurve(); MRwheelFriction.extremumSlip = middleRightCollider.sidewaysFriction.extremumSlip; MRWextremumSlip = middleRightCollider.sidewaysFriction.extremumSlip; MRwheelFriction.extremumValue = middleRightCollider.sidewaysFriction.extremumValue; MRwheelFriction.asymptoteSlip = middleRightCollider.sidewaysFriction.asymptoteSlip; MRwheelFriction.asymptoteValue = middleRightCollider.sidewaysFriction.asymptoteValue; MRwheelFriction.stiffness = middleRightCollider.sidewaysFriction.stiffness; RLwheelFriction = new WheelFrictionCurve(); RLwheelFriction.extremumSlip = rearLeftCollider.sidewaysFriction.extremumSlip; RLWextremumSlip = rearLeftCollider.sidewaysFriction.extremumSlip; RLwheelFriction.extremumValue = rearLeftCollider.sidewaysFriction.extremumValue; RLwheelFriction.asymptoteSlip = rearLeftCollider.sidewaysFriction.asymptoteSlip; RLwheelFriction.asymptoteValue = rearLeftCollider.sidewaysFriction.asymptoteValue; RLwheelFriction.stiffness = rearLeftCollider.sidewaysFriction.stiffness; RRwheelFriction = new WheelFrictionCurve(); RRwheelFriction.extremumSlip = rearRightCollider.sidewaysFriction.extremumSlip; RRWextremumSlip = rearRightCollider.sidewaysFriction.extremumSlip; RRwheelFriction.extremumValue = rearRightCollider.sidewaysFriction.extremumValue; RRwheelFriction.asymptoteSlip = rearRightCollider.sidewaysFriction.asymptoteSlip; RRwheelFriction.asymptoteValue = rearRightCollider.sidewaysFriction.asymptoteValue; RRwheelFriction.stiffness = rearRightCollider.sidewaysFriction.stiffness; if(carEngineSound != null){ initialCarEngineSoundPitch = carEngineSound.pitch; } if(useUI){ InvokeRepeating("CarSpeedUI", 0f, 0.1f); }else if(!useUI){ if(carSpeedText != null){ carSpeedText.text = "0"; } } if(useSounds){ InvokeRepeating("CarSounds", 0f, 0.1f); }else if(!useSounds){ if(carEngineSound != null){ carEngineSound.Stop(); } if(tireScreechSound != null){ tireScreechSound.Stop(); } } if(!useEffects){ if(RLWParticleSystem != null){ RLWParticleSystem.Stop(); } if(RRWParticleSystem != null){ RRWParticleSystem.Stop(); } if(MLWParticleSystem != null){ MLWParticleSystem.Stop(); } if(MRWParticleSystem != null){ MRWParticleSystem.Stop(); } if(RLWTireSkid != null){ RLWTireSkid.emitting = false; } if(RRWTireSkid != null){ RRWTireSkid.emitting = false; } if(MLWTireSkid != null){ MLWTireSkid.emitting = false; } if(MRWTireSkid != null){ MRWTireSkid.emitting = false; } } if(useTouchControls){ if(throttleButton != null && reverseButton != null && turnRightButton != null && turnLeftButton != null && handbrakeButton != null){ throttlePTI = throttleButton.GetComponent<PrometeoTouchInput>(); reversePTI = reverseButton.GetComponent<PrometeoTouchInput>(); turnLeftPTI = turnLeftButton.GetComponent<PrometeoTouchInput>(); turnRightPTI = turnRightButton.GetComponent<PrometeoTouchInput>(); handbrakePTI = handbrakeButton.GetComponent<PrometeoTouchInput>(); touchControlsSetup = true; }else{ String ex = "Touch controls are not completely set up. You must drag and drop your scene buttons in the" + " PrometeoTruckController component."; Debug.LogWarning(ex); } } } void Update() { carSpeed = (2 * Mathf.PI * frontLeftCollider.radius * frontLeftCollider.rpm * 60) / 1000; localVelocityX = transform.InverseTransformDirection(carRigidbody.velocity).x; localVelocityZ = transform.InverseTransformDirection(carRigidbody.velocity).z; if (useTouchControls && touchControlsSetup){ if(throttlePTI.buttonPressed){ CancelInvoke("DecelerateCar"); deceleratingCar = false; GoForward(); } if(reversePTI.buttonPressed){ CancelInvoke("DecelerateCar"); deceleratingCar = false; GoReverse(); } if(turnLeftPTI.buttonPressed){ TurnLeft(); } if(turnRightPTI.buttonPressed){ TurnRight(); } if(handbrakePTI.buttonPressed){ CancelInvoke("DecelerateCar"); deceleratingCar = false; Handbrake(); } if(!handbrakePTI.buttonPressed){ RecoverTraction(); } if((!throttlePTI.buttonPressed && !reversePTI.buttonPressed)){ ThrottleOff(); } if((!reversePTI.buttonPressed && !throttlePTI.buttonPressed) && !handbrakePTI.buttonPressed && !deceleratingCar){ InvokeRepeating("DecelerateCar", 0f, 0.1f); deceleratingCar = true; } if(!turnLeftPTI.buttonPressed && !turnRightPTI.buttonPressed && steeringAxis != 0f){ ResetSteeringAngle(); } }else{ if(Input.GetKey(KeyCode.W)){ CancelInvoke("DecelerateCar"); deceleratingCar = false; GoForward(); } if(Input.GetKey(KeyCode.S)){ CancelInvoke("DecelerateCar"); deceleratingCar = false; GoReverse(); } if(Input.GetKey(KeyCode.A)){ TurnLeft(); } if(Input.GetKey(KeyCode.D)){ TurnRight(); } if(Input.GetKey(KeyCode.Space)){ CancelInvoke("DecelerateCar"); deceleratingCar = false; Handbrake(); } if(Input.GetKeyUp(KeyCode.Space)){ RecoverTraction(); } if((!Input.GetKey(KeyCode.S) && !Input.GetKey(KeyCode.W))){ ThrottleOff(); } if((!Input.GetKey(KeyCode.S) && !Input.GetKey(KeyCode.W)) && !Input.GetKey(KeyCode.Space) && !deceleratingCar){ InvokeRepeating("DecelerateCar", 0f, 0.1f); deceleratingCar = true; } if(!Input.GetKey(KeyCode.A) && !Input.GetKey(KeyCode.D) && steeringAxis != 0f){ ResetSteeringAngle(); } } AnimateWheelMeshes(); } public void CarSpeedUI(){ if(useUI){ try{ float absoluteCarSpeed = Mathf.Abs(carSpeed); carSpeedText.text = Mathf.RoundToInt(absoluteCarSpeed).ToString(); }catch(Exception ex){ Debug.LogWarning(ex); } } } public void CarSounds(){ if(useSounds){ try{ if(carEngineSound != null){ float engineSoundPitch = initialCarEngineSoundPitch + (Mathf.Abs(carRigidbody.velocity.magnitude) / 25f); carEngineSound.pitch = engineSoundPitch; } if((isDrifting) || (isTractionLocked && Mathf.Abs(carSpeed) > 12f)){ if(!tireScreechSound.isPlaying){ tireScreechSound.Play(); } }else if((!isDrifting) && (!isTractionLocked || Mathf.Abs(carSpeed) < 12f)){ tireScreechSound.Stop(); } }catch(Exception ex){ Debug.LogWarning(ex); } }else if(!useSounds){ if(carEngineSound != null && carEngineSound.isPlaying){ carEngineSound.Stop(); } if(tireScreechSound != null && tireScreechSound.isPlaying){ tireScreechSound.Stop(); } } } // //STEERING METHODS // public void TurnLeft(){ steeringAxis = steeringAxis - (Time.deltaTime * 10f * steeringSpeed); if(steeringAxis < -1f){ steeringAxis = -1f; } var steeringAngle = steeringAxis * maxSteeringAngle; frontLeftCollider.steerAngle = Mathf.Lerp(frontLeftCollider.steerAngle, steeringAngle, steeringSpeed); frontRightCollider.steerAngle = Mathf.Lerp(frontRightCollider.steerAngle, steeringAngle, steeringSpeed); } public void TurnRight(){ steeringAxis = steeringAxis + (Time.deltaTime * 10f * steeringSpeed); if(steeringAxis > 1f){ steeringAxis = 1f; } var steeringAngle = steeringAxis * maxSteeringAngle; frontLeftCollider.steerAngle = Mathf.Lerp(frontLeftCollider.steerAngle, steeringAngle, steeringSpeed); frontRightCollider.steerAngle = Mathf.Lerp(frontRightCollider.steerAngle, steeringAngle, steeringSpeed); } public void ResetSteeringAngle(){ if(steeringAxis < 0f){ steeringAxis = steeringAxis + (Time.deltaTime * 10f * steeringSpeed); }else if(steeringAxis > 0f){ steeringAxis = steeringAxis - (Time.deltaTime * 10f * steeringSpeed); } if(Mathf.Abs(frontLeftCollider.steerAngle) < 1f){ steeringAxis = 0f; } var steeringAngle = steeringAxis * maxSteeringAngle; frontLeftCollider.steerAngle = Mathf.Lerp(frontLeftCollider.steerAngle, steeringAngle, steeringSpeed); frontRightCollider.steerAngle = Mathf.Lerp(frontRightCollider.steerAngle, steeringAngle, steeringSpeed); } void AnimateWheelMeshes(){ try{ Quaternion FLWRotation; Vector3 FLWPosition; frontLeftCollider.GetWorldPose(out FLWPosition, out FLWRotation); frontLeftMesh.transform.position = FLWPosition; frontLeftMesh.transform.rotation = FLWRotation; Quaternion FRWRotation; Vector3 FRWPosition; frontRightCollider.GetWorldPose(out FRWPosition, out FRWRotation); frontRightMesh.transform.position = FRWPosition; frontRightMesh.transform.rotation = FRWRotation; Quaternion MLWRotation; Vector3 MLWPosition; middleLeftCollider.GetWorldPose(out MLWPosition, out MLWRotation); middleLeftMesh.transform.position = MLWPosition; middleLeftMesh.transform.rotation = MLWRotation; Quaternion MRWRotation; Vector3 MRWPosition; middleRightCollider.GetWorldPose(out MRWPosition, out MRWRotation); middleRightMesh.transform.position = MRWPosition; middleRightMesh.transform.rotation = MRWRotation; Quaternion RLWRotation; Vector3 RLWPosition; rearLeftCollider.GetWorldPose(out RLWPosition, out RLWRotation); rearLeftMesh.transform.position = RLWPosition; rearLeftMesh.transform.rotation = RLWRotation; Quaternion RRWRotation; Vector3 RRWPosition; rearRightCollider.GetWorldPose(out RRWPosition, out RRWRotation); rearRightMesh.transform.position = RRWPosition; rearRightMesh.transform.rotation = RRWRotation; }catch(Exception ex){ Debug.LogWarning(ex); } } // //ENGINE AND BRAKING METHODS // public void GoForward(){ if(Mathf.Abs(localVelocityX) > 2.5f){ isDrifting = true; DriftCarPS(); }else{ isDrifting = false; DriftCarPS(); } throttleAxis = throttleAxis + (Time.deltaTime * 3f); if(throttleAxis > 1f){ throttleAxis = 1f; } if(localVelocityZ < -1f){ Brakes(); }else{ if(Mathf.RoundToInt(carSpeed) < maxSpeed){ frontLeftCollider.brakeTorque = 0; frontLeftCollider.motorTorque = (accelerationMultiplier * 50f) * throttleAxis; frontRightCollider.brakeTorque = 0; frontRightCollider.motorTorque = (accelerationMultiplier * 50f) * throttleAxis; middleLeftCollider.brakeTorque = 0; middleLeftCollider.motorTorque = (accelerationMultiplier * 50f) * throttleAxis; middleRightCollider.brakeTorque = 0; middleRightCollider.motorTorque = (accelerationMultiplier * 50f) * throttleAxis; rearLeftCollider.brakeTorque = 0; rearLeftCollider.motorTorque = (accelerationMultiplier * 50f) * throttleAxis; rearRightCollider.brakeTorque = 0; rearRightCollider.motorTorque = (accelerationMultiplier * 50f) * throttleAxis; }else { frontLeftCollider.motorTorque = 0; frontRightCollider.motorTorque = 0; middleLeftCollider.motorTorque = 0; middleRightCollider.motorTorque = 0; rearLeftCollider.motorTorque = 0; rearRightCollider.motorTorque = 0; } } } public void GoReverse(){ if(Mathf.Abs(localVelocityX) > 2.5f){ isDrifting = true; DriftCarPS(); }else{ isDrifting = false; DriftCarPS(); } throttleAxis = throttleAxis - (Time.deltaTime * 3f); if(throttleAxis < -1f){ throttleAxis = -1f; } if(localVelocityZ > 1f){ Brakes(); }else{ if(Mathf.Abs(Mathf.RoundToInt(carSpeed)) < maxReverseSpeed){ frontLeftCollider.brakeTorque = 0; frontLeftCollider.motorTorque = (accelerationMultiplier * 50f) * throttleAxis; frontRightCollider.brakeTorque = 0; frontRightCollider.motorTorque = (accelerationMultiplier * 50f) * throttleAxis; middleLeftCollider.brakeTorque = 0; middleLeftCollider.motorTorque = (accelerationMultiplier * 50f) * throttleAxis; middleRightCollider.brakeTorque = 0; middleRightCollider.motorTorque = (accelerationMultiplier * 50f) * throttleAxis; rearLeftCollider.brakeTorque = 0; rearLeftCollider.motorTorque = (accelerationMultiplier * 50f) * throttleAxis; rearRightCollider.brakeTorque = 0; rearRightCollider.motorTorque = (accelerationMultiplier * 50f) * throttleAxis; }else { frontLeftCollider.motorTorque = 0; frontRightCollider.motorTorque = 0; middleLeftCollider.motorTorque = 0; middleRightCollider.motorTorque = 0; rearLeftCollider.motorTorque = 0; rearRightCollider.motorTorque = 0; } } } public void ThrottleOff(){ frontLeftCollider.motorTorque = 0; frontRightCollider.motorTorque = 0; middleLeftCollider.motorTorque = 0; middleRightCollider.motorTorque = 0; rearLeftCollider.motorTorque = 0; rearRightCollider.motorTorque = 0; } public void DecelerateCar(){ if(Mathf.Abs(localVelocityX) > 2.5f){ isDrifting = true; DriftCarPS(); }else{ isDrifting = false; DriftCarPS(); } if(throttleAxis != 0f){ if(throttleAxis > 0f){ throttleAxis = throttleAxis - (Time.deltaTime * 10f); }else if(throttleAxis < 0f){ throttleAxis = throttleAxis + (Time.deltaTime * 10f); } if(Mathf.Abs(throttleAxis) < 0.15f){ throttleAxis = 0f; } } carRigidbody.velocity = carRigidbody.velocity * (1f / (1f + (0.025f * decelerationMultiplier))); frontLeftCollider.motorTorque = 0; frontRightCollider.motorTorque = 0; middleLeftCollider.motorTorque = 0; middleRightCollider.motorTorque = 0; rearLeftCollider.motorTorque = 0; rearRightCollider.motorTorque = 0; if(carRigidbody.velocity.magnitude < 0.25f){ carRigidbody.velocity = Vector3.zero; CancelInvoke("DecelerateCar"); } } public void Brakes(){ frontLeftCollider.brakeTorque = brakeForce; frontRightCollider.brakeTorque = brakeForce; middleLeftCollider.brakeTorque = brakeForce; middleRightCollider.brakeTorque = brakeForce; rearLeftCollider.brakeTorque = brakeForce; rearRightCollider.brakeTorque = brakeForce; } public void Handbrake(){ CancelInvoke("RecoverTraction"); driftingAxis = driftingAxis + (Time.deltaTime); float secureStartingPoint = driftingAxis * FLWextremumSlip * handbrakeDriftMultiplier; if(secureStartingPoint < FLWextremumSlip){ driftingAxis = FLWextremumSlip / (FLWextremumSlip * handbrakeDriftMultiplier); } if(driftingAxis > 1f){ driftingAxis = 1f; } if(Mathf.Abs(localVelocityX) > 2.5f){ isDrifting = true; }else{ isDrifting = false; } if(driftingAxis < 1f){ FLwheelFriction.extremumSlip = FLWextremumSlip * handbrakeDriftMultiplier * driftingAxis; frontLeftCollider.sidewaysFriction = FLwheelFriction; FRwheelFriction.extremumSlip = FRWextremumSlip * handbrakeDriftMultiplier * driftingAxis; frontRightCollider.sidewaysFriction = FRwheelFriction; MLwheelFriction.extremumSlip = MLWextremumSlip * handbrakeDriftMultiplier * driftingAxis; middleLeftCollider.sidewaysFriction = MLwheelFriction; MRwheelFriction.extremumSlip = MRWextremumSlip * handbrakeDriftMultiplier * driftingAxis; middleRightCollider.sidewaysFriction = MRwheelFriction; RLwheelFriction.extremumSlip = RLWextremumSlip * handbrakeDriftMultiplier * driftingAxis; rearLeftCollider.sidewaysFriction = RLwheelFriction; RRwheelFriction.extremumSlip = RRWextremumSlip * handbrakeDriftMultiplier * driftingAxis; rearRightCollider.sidewaysFriction = RRwheelFriction; } isTractionLocked = true; DriftCarPS(); } public void DriftCarPS(){ if(useEffects){ try{ if(isDrifting){ RLWParticleSystem.Play(); RRWParticleSystem.Play(); MLWParticleSystem.Play(); MRWParticleSystem.Play(); }else if(!isDrifting){ RLWParticleSystem.Stop(); RRWParticleSystem.Stop(); MLWParticleSystem.Stop(); MRWParticleSystem.Stop(); } }catch(Exception ex){ Debug.LogWarning(ex); } try{ if((isTractionLocked || Mathf.Abs(localVelocityX) > 5f) && Mathf.Abs(carSpeed) > 12f){ RLWTireSkid.emitting = true; RRWTireSkid.emitting = true; MLWTireSkid.emitting = true; MRWTireSkid.emitting = true; }else { RLWTireSkid.emitting = false; RRWTireSkid.emitting = false; MLWTireSkid.emitting = false; MRWTireSkid.emitting = false; } }catch(Exception ex){ Debug.LogWarning(ex); } }else if(!useEffects){ if(RLWParticleSystem != null){ RLWParticleSystem.Stop(); } if(RRWParticleSystem != null){ RRWParticleSystem.Stop(); } if(MLWParticleSystem != null){ MLWParticleSystem.Stop(); } if(MRWParticleSystem != null){ MRWParticleSystem.Stop(); } if(RLWTireSkid != null){ RLWTireSkid.emitting = false; } if(RRWTireSkid != null){ RRWTireSkid.emitting = false; } if(MLWTireSkid != null){ MLWTireSkid.emitting = false; } if(MRWTireSkid != null){ MRWTireSkid.emitting = false; } } } public void RecoverTraction(){ isTractionLocked = false; driftingAxis = driftingAxis - (Time.deltaTime / 1.5f); if(driftingAxis < 0f){ driftingAxis = 0f; } if(FLwheelFriction.extremumSlip > FLWextremumSlip){ FLwheelFriction.extremumSlip = FLWextremumSlip * handbrakeDriftMultiplier * driftingAxis; frontLeftCollider.sidewaysFriction = FLwheelFriction; FRwheelFriction.extremumSlip = FRWextremumSlip * handbrakeDriftMultiplier * driftingAxis; frontRightCollider.sidewaysFriction = FRwheelFriction; MLwheelFriction.extremumSlip = MLWextremumSlip * handbrakeDriftMultiplier * driftingAxis; middleLeftCollider.sidewaysFriction = MLwheelFriction; MRwheelFriction.extremumSlip = MRWextremumSlip * handbrakeDriftMultiplier * driftingAxis; middleRightCollider.sidewaysFriction = MRwheelFriction; RLwheelFriction.extremumSlip = RLWextremumSlip * handbrakeDriftMultiplier * driftingAxis; rearLeftCollider.sidewaysFriction = RLwheelFriction; RRwheelFriction.extremumSlip = RRWextremumSlip * handbrakeDriftMultiplier * driftingAxis; rearRightCollider.sidewaysFriction = RRwheelFriction; Invoke("RecoverTraction", Time.deltaTime); }else if (FLwheelFriction.extremumSlip < FLWextremumSlip){ FLwheelFriction.extremumSlip = FLWextremumSlip; frontLeftCollider.sidewaysFriction = FLwheelFriction; FRwheelFriction.extremumSlip = FRWextremumSlip; frontRightCollider.sidewaysFriction = FRwheelFriction; MLwheelFriction.extremumSlip = MLWextremumSlip; middleLeftCollider.sidewaysFriction = MLwheelFriction; MRwheelFriction.extremumSlip = MRWextremumSlip; middleRightCollider.sidewaysFriction = MRwheelFriction; RLwheelFriction.extremumSlip = RLWextremumSlip; rearLeftCollider.sidewaysFriction = RLwheelFriction; RRwheelFriction.extremumSlip = RRWextremumSlip; rearRightCollider.sidewaysFriction = RRwheelFriction; driftingAxis = 0f; } }
}
происходит эта ошибка
Can't add script component 'PrometeoTruckController' because the script class cannot be found. Make sure that there are no compile errors and that the file name and class name match.
The error you're encountering typically occurs in Unity when the script class cannot be found or isn't compiling correctly. Here are the most common reasons for this issue and how to resolve them:
File Name and Class Name Mismatch:
PrometeoTruckController, so the file must be named PrometeoTruckController.cs.Compilation Errors in the Script:
Window -> General -> Console).Missing or Incorrectly Referenced Dependencies:
PrometeoTruckController are present in your project and are error-free.PrometeoTouchInput class, which your script references. If this class is missing or has errors, it can prevent PrometeoTruckController from compiling.Namespace Issues:
Script Placement in the Project Hierarchy:
Assets or a subfolder thereof. Unity only compiles scripts within the Assets directory.Assets folder won't be compiled by Unity.Unity Version Compatibility:
Special Characters and Encoding:
Steps to Resolve the Issue:
Check the File Name:
PrometeoTruckController.cs if it's not already named that.Inspect the Console for Errors:
Verify All Dependencies:
PrometeoTouchInput and any other custom scripts are present and error-free.PrometeoTouchInput script, you'll need to obtain it or comment out related code for testing.Test the Script in Isolation:
PrometeoTruckController.cs script to the project.Review the Script for Errors:
{ have corresponding closing brackets }.Reimport All Assets:
Assets -> Reimport All.Additional Tips:
Example:
csharp// Ensure the script file is named PrometeoTruckController.cs public class PrometeoTruckController : MonoBehaviour { // Your script content }
Conclusion:
By ensuring that the file name matches the class name, fixing any compilation errors, and verifying that all dependencies are correctly referenced and error-free, you should be able to resolve the error and successfully attach the script to your GameObject.
объясни на русском
Ошибка, с которой вы столкнулись, обычно возникает в Unity, когда скрипт не может быть найден или не компилируется правильно. Вот наиболее распространенные причины этой проблемы и способы ее решения:
Несоответствие имени файла и класса:
PrometeoTruckController, поэтому файл должен называться PrometeoTruckController.cs.Ошибки компиляции в скрипте:
Window -> General -> Console).Отсутствующие или некорректно подключенные зависимости:
PrometeoTruckController, присутствуют в вашем проекте и не содержат ошибок.PrometeoTouchInput, который используется в вашем скрипте. Если этот класс отсутствует или содержит ошибки, это может помешать компиляции PrometeoTruckController.Проблемы с пространствами имен (namespaces):
Расположение скрипта в структуре проекта:
Assets или ее подпапок. Unity компилирует скрипты только внутри директории Assets.Assets, не будут скомпилированы Unity.Совместимость с версией Unity:
Специальные символы и кодировка:
Шаги для решения проблемы:
Проверьте имя файла:
PrometeoTruckController.cs, если он еще не так назван.Проверьте консоль на наличие ошибок:
Проверьте все зависимости:
PrometeoTouchInput и любые другие пользовательские скрипты присутствуют и не содержат ошибок.PrometeoTouchInput, вам нужно его получить или закомментировать связанные части кода для тестирования.Протестируйте скрипт отдельно:
PrometeoTruckController.cs в проект.Просмотрите скрипт на наличие ошибок:
{ имеют соответствующие закрывающие }.Переимпортируйте все ресурсы:
Assets -> Reimport All.Дополнительные советы:
Пример:
csharp// Убедитесь, что файл скрипта назван PrometeoTruckController.cs public class PrometeoTruckController : MonoBehaviour { // Ваш код скрипта }
Заключение:
Убедившись, что имя файла совпадает с именем класса, исправив ошибки компиляции и проверив, что все зависимости правильно подключены и не содержат ошибок, вы сможете решить проблему и успешно прикрепить скрипт к вашему объекту.
а из за чего это возникает когда я закидываю любой скрипт на этот объект
Если у вас возникает такая ошибка при попытке добавить любой скрипт на объект, это указывает на то, что в вашем проекте Unity есть ошибки компиляции, которые препятствуют правильной работе всех скриптов. В Unity, если есть хотя бы одна ошибка в каком-либо скрипте, это может привести к тому, что никакие скрипты не будут компилироваться, и вы не сможете добавить их на объекты.
Почему это происходит:
Ошибки компиляции в проекте:
Неправильные настройки скриптов или проекта:
Assets, Unity не будет их компилировать.Что нужно сделать:
Проверьте консоль на наличие ошибок:
Window -> General -> Console).Исправьте все ошибки компиляции:
Проверьте все скрипты в проекте:
Переимпортируйте все ресурсы:
Assets -> Reimport All.Создайте новый пустой объект и протестируйте:
GameObject -> Create Empty).Проверьте кодировку файлов скриптов:
Проверьте наличие необходимых классов и зависимостей:
PrometeoTouchInput, убедитесь, что этот скрипт есть в проекте и работает корректно.Дополнительные рекомендации:
Пример действий:
Откройте консоль и найдите ошибки:

Исправьте первую найденную ошибку:
Assets/Scripts/MyScript.cs(10,15): error CS1002: ; expectedMyScript.cs к строке 10, столбцу 15, и добавьте недостающую точку с запятой.После исправления ошибок перезапустите Unity:
Заключение:
Ошибка возникает из-за того, что в вашем проекте есть ошибки компиляции, которые мешают Unity правильно скомпилировать скрипты. Исправив все ошибки в консоли и убедившись, что все скрипты корректны, вы сможете добавлять скрипты на объекты без проблем.
Если после выполнения всех шагов проблема сохраняется, возможно, стоит проверить сам объект, на который вы пытаетесь добавить скрипт:
GameObject, а не, например, ассетом модели или prefab, который не предназначен для добавления скриптов.Надеюсь, эта информация поможет вам решить проблему. Если у вас есть дополнительные вопросы или нужна помощь с конкретными ошибками из консоли, пожалуйста, поделитесь ими, и я постараюсь помочь.
а из за чего это может быть когда я кидаю скрипты на любые объекты
Если у вас возникает ошибка при попытке добавить скрипты на любые объекты в Unity, это означает, что в вашем проекте присутствуют ошибки компиляции, которые мешают корректной работе всех скриптов. В Unity, если хотя бы один скрипт содержит ошибку, это может привести к тому, что ни один скрипт не будет компилироваться, и вы не сможете добавить их на объекты.
Возможные причины и решения:
Ошибки компиляции в скриптах:
Window -> General -> Console) и проверьте наличие сообщений об ошибках (они выделены красным цветом). Исправьте все обнаруженные ошибки в скриптах. Обратите особое внимание на первую ошибку, так как последующие могут быть ее следствием.Несоответствие имени файла и класса:
MyScript, то файл должен называться MyScript.cs.Отсутствие необходимых скриптов или классов:
PrometeoTouchInput, убедитесь, что они правильно подключены и работают.Неправильное расположение скриптов:
Assets, и Unity не может их обнаружить и скомпилировать.Assets или ее подпапок. Проверьте, что ваши скрипты расположены правильно.Проблемы с кодировкой или специальными символами:
Конфликты версий или устаревший API:
Шаги для решения проблемы:
Проверка консоли на наличие ошибок:
Window -> General -> Console).Исправление ошибок в скриптах:
Проверка соответствия имен файлов и классов:
PlayerController, то файл должен быть PlayerController.cs.Проверка наличия всех зависимостей:
Переимпорт всех активов:
Assets -> Reimport All.Перезапуск Unity:
Создание тестового проекта:
Обновление Unity и инструментов:
Дополнительные рекомендации:
Заключение:
Проблема с добавлением скриптов на объекты в Unity обычно связана с ошибками компиляции в вашем проекте. Исправив все ошибки в консоли и убедившись, что все скрипты корректны и правильно настроены, вы сможете без проблем добавлять скрипты на объекты.
Если после выполнения всех этих шагов проблема все еще сохраняется, рекомендуем обратиться на форумы сообщества Unity или в документацию Unity для получения дополнительной помощи. Пожалуйста, предоставьте детали ошибок из консоли, чтобы сообщество могло более эффективно помочь вам.