希望在我的Unity C#脚本中提供有关SOLID原则的建议



我正在努力理解SOLID,并想知道如何更好地格式化我的Unity C#脚本以符合这些原则。我将提供脚本,然后解释:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
public float speed = 12f;
public float gravity = -9.81f;
Vector3 velocity;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
private bool isGrounded;
void Update()
{
GroundCheck();
Movement();
Gravity();
}
private void GroundCheck()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if(isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
}
private void Movement()
{
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
}
private void Gravity()
{
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}

这是一个处理角色移动的脚本,但还执行地面检查和玩家的重力。我见过在同一脚本中添加新功能和新类时使用的接口,但我认为就本代码而言,最好将每个功能分离为一个函数,并在更新PlayerMovement类时调用它们。我决定使用一个类,因为出于性能原因,我担心在这个脚本中运行三个带有三个Update方法的类。从SOLID的角度来看,有没有更好的方法来处理这个脚本的组织?我的想法是,如果我想扩展这些功能,我可以在每个功能中都这样做,如果我需要新的功能,我也可以创建更多的功能。

您可以有一个单独的类,该类具有GroundCheck((、Movement((、Gravity((方法,然后您可以从PlayerMovement类访问该类。如果你让你的方法是静态的,你就可以访问它们。这样,您将在PlayerMovement类和Update((方法中拥有公共和私有字段。因此,您调用Update((中的方法,并在括号中添加所需的参数。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
public float speed = 12f;
public float gravity = -9.81f;
Vector3 velocity;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
private bool isGrounded;

Movement movement;
void Start()
{
movement = FindObjectOfType<Movement>();
}
void Update()
{
movement.GroundCheck(isGrounded, groundCheck, groundDistance, groundMask, velocity);
movement.Movement(this.gameObject, controller, speed);
movement.Gravity(velocity, gravity, controller);
}   
}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
static public void GroundCheck(bool isGrounded, Transform groundCheck, float groundDistance, LayerMask groundMask, Vector3 velocity)
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if(isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
}
static public void Movement(GameObject playerMovement, CharacterController controller, float speed)
{
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = playerMovement.transform.right * x + playerMovement.transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
}
static public void Gravity(Vector3 velocity, float gravity, CharacterController controller)
{
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}

最新更新