我正在学习Unity中的面向对象编程,并发现了使用oop构建代码的游戏,问题是我无法弄清楚"private bool IsInitialized => _bulletPool != null;"这行代码的含义。
我已经了解了lambda表达式,并且理解它可以像UnityAction一样使用,或用于编写更短的函数。
using System;
using UnityEngine;
using UnityEngine.Events;
[RequireComponent(typeof(CapsuleCollider2D))]
[RequireComponent(typeof(ShipAudio))]
public abstract class Ship : MonoBehaviour
{
[SerializeField] private Vector2 _shootDirection;
private BulletPool _bulletPool;
protected CapsuleCollider2D Collider;
private bool IsInitialized => _bulletPool != null; //this line
public event UnityAction Shooted;
public event UnityAction TookDamage;
public event UnityAction Died;
private void Awake()
{
if (_shootDirection == Vector2.zero)
throw new ArgumentException(nameof(_shootDirection));
Collider = GetComponent<CapsuleCollider2D>();
Collider.isTrigger = true;
}
public void Init(BulletPool bulletPool)
{
_bulletPool = bulletPool;
}
public void TakeDamage()
{
OnTakeDamage();
TookDamage?.Invoke();
}
public void Die()
{
OnDie();
Died?.Invoke();
}
public void Shoot()
{
if (IsInitialized == false)
throw new Exception("Impossible to shoot. Bullet pool is not stated");
if (_bulletPool.TryGetObject(out Bullet bullet) == false)
throw new Exception("Impossible to spawn bullet");
bullet.Show();
bullet.transform.position = transform.position;
bullet.Init(_shootDirection);
Shooted?.Invoke();
}
protected abstract void OnTakeDamage();
protected abstract void OnDie();
}
bulletpool != null
是一个表达式,该表达式的值并没有被赋给IsInitialized
。该表达式本身被分配为IsInitialized
的 getter 方法的主体。这意味着每次获取IsInitialized
的值时,都会在那一刻计算该表达式的值。 - Logarr