Why reference Laser this way?

Hi Rick! When doing one of the challenges in the video I noticed you referenced the Laser differently and I’m wondering if I’m doing something wrong.

This is how I did it –

  1. In the Laser.cs class definition:
    Laser laser;
  2. In Start():
    laser = GetComponent();

This is how you showed us to do it –
[SerializeField] GameObject laserPrefab;

Hi,

Welcome to our community! :slight_smile:

We need a prefab, which is a game object with components attached, but it is not in our scene. In your example, you are looking for a component.

The question is: Does your approach work?

Thanks! Glad to be here.

It was working to reference it that way, but I didn’t keep it because as I continue on I see that there’s no laser.cs file in the instructor’s project. I guess what I was getting at was “what is the best way to reference these things” but the course has since started to explain this.

Since we have multiple Laser objects in our scene, using FindObjectOfType is very likely not a good idea because it returns the “first” object it finds in the scene, whatever Unity defines as “first”. This means that it might well be that we get the “wrong” object. GetComponent is more specific because it looks for an object attached to the same game object on which you call GetComponent.


See also:

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms