#Object Reference Issue

1 messages · Page 1 of 1 (latest)

opal basin
#

Hello There, I Am Currently Following A Tutorial On How To Make A Multiplayer Game In Unity Using Photon.

When I Try And Shoot At The Player, I Get This Error Message

Here Is The Code For SingleShotCode.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SingleShotGun : Gun
{
    [SerializeField] Camera cam;

    public override void Use()
    {
        Shoot();
    }

    void Shoot()
    {
        Ray ray = cam.ViewportPointToRay(new Vector3(0.5f, 0.5f));
        ray.origin = cam.transform.position;
        if (Physics.Raycast(ray, out RaycastHit hit))
        {
            hit.collider.gameObject.GetComponent<IDamageable>().TakeDamage(((GunInfo)itemInfo).damage);
        }
    }
}

https://cdn.discordapp.com/attachments/1153029763657633903/1153029763812819014/image.png

sudden igloo
opal basin
#

it was when i tried shooting at a other player that error would show up

sudden igloo
#

Identify what is null. Then take debugging steps to see why it's the case (log the name of the object you hit)

#

Should probably be using TryGetComponent since you do not filter out the raycast results with a layer mask for example.

if (Physics.Raycast(..., out RaycastHit hit) && hit.collider.GetComponent(out IDamageable dmg))
{
    dmg.TakeDamage(stuff);
}
else
{
    // No hit or not damageable, handle
}
opal basin
#

is it possible for a preview of what the code will look like from the code of the first message i sent or no ?