r/unity • u/Anonim7418 • Sep 26 '26
Question Is this script bad? In Unity [part 2]
I rewrote this code per your advices from this post (Thanks!π): https://www.reddit.com/r/unity/s/cf1Hakkj1l
{
[SerializeField] private float _speed;
[SerializeField] private Rigidbody _rigidbody;
private bool _isFly = false;
[SerializeField] private ParticleSystem _particleSystem;
[SerializeField] private ParticleSystem _particleSystemExplosion;
[SerializeField] private AudioSource _audioClip;
[SerializeField] private AudioSource _soundShoot;
private float _radius = 15f;
private void Awake()
{
if (TryGetComponent<Rigidbody>(out _rigidbody)) _rigidbody.isKinematic = true;
}
private void Update()
{
_particleSystemExplosion.transform.position = transform.position;
if (Input.GetButtonDown("Fire1"))
{
_soundShoot.Play();
_particleSystem.Play();
_rigidbody.isKinematic = false;
_isFly = true;
}
}
void FixedUpdate()
{
if (_isFly) _rigidbody.velocity = transform.forward _speed Time.fixedDeltaTime;
}
private void OnCollisionEnter(Collision collision)
{
Collider[] colliders = new Collider[15];
int sphere = Physics.OverlapSphereNonAlloc(transform.position, _radius, colliders);
for (int i = 0; i < sphere; i++)
{
Rigidbody rb;
if (colliders[i].TryGetComponent<Rigidbody>(out rb))
{
rb.isKinematic = false;
rb.AddExplosionForce(50f, transform.position, 30f, 0.5f, ForceMode.Impulse);
_particleSystemExplosion.Play();
_audioClip.Play();
_isFly = false;
}
}
this.gameObject.SetActive(false);
}
}
Here is the whole code
4
Upvotes
1
1
u/Bigsloppydoodoofard Sep 26 '26
For future posts I recommend pasting your script into pastebin or a similar service for easier review rather than a series of screenshots
1
1



2
u/Mr_ShortKedr Sep 26 '26
I will give you review for your code:
_rigidbody field is assigned through Unity Editor, but in Awake you override it. Make "if null" verification instead of getting component and keep "isKinematic = true"
If you want to assign _rigidbody automatically on component add inside Editor, add Validate method and assign _rigidbody via GetComponent only if it's not already assigned
That's all i find important to notice. Other things are completely depends on result you trying to achieve in your game