I am about to go nuts :( I cant access the active camera in a class instance "cannot convert argument 2 from Nil to Vector3"

Godot Version



When I run the game I am getting this error once clicked :frowning: I do not understand what I am doing wrong here.

Invalid type in function 'intersects_ray' in base 'Plane'. Cannot convert argument 2 from Nil to Vector3.

I converted this code from a boiler plate code, so the plane actual intersection actually works I know these are the actual functions and the outputs. I am speculating, I am guessing that the camera ray is never calculated.

I have this sceneutil class and an instancing itk like this

    var util=SceneUtil.new()
    var hit:Vector3=util.raycast_to_plane()


class_name SceneUtil extends Node3D

@onready var pos: Vector3;
@onready var camera_active: Camera3D = get_viewport().get_camera_3d()
@onready var origin:Vector3 = camera_active.project_ray_origin( get_viewport().get_mouse_position() )
@onready var end = camera_active.project_ray_normal( get_viewport().get_mouse_position() )

func get_active_camera() -> Camera3D:
    return camera_active

func raycast_to_scene() -> Dictionary:
    var query
    var hit:Dictionary
    origin = camera_active.project_ray_origin( get_viewport().get_mouse_position() )
    end = camera_active.project_ray_normal( get_viewport().get_mouse_position() )
    query=PhysicsRayQueryParameters3D.create(origin, end)
    var space_state = get_world_3d().direct_space_state
    return hit

func raycast_to_plane(dir:Vector3=Vector3(0,1,0), dist:float=0.0 )->Vector3:
    var hit
    var cursorPlane = Plane(dir,dist)
    hit = cursorPlane.intersects_ray(origin,end )
    return hit

When using @onready the variables won’t be initialized until the node is ready. You aren’t adding the node to the scene tree so it will never be ready.

1 Like

Hey thanks for the reply. What is the actual right way to go about it? How do I " add" it to the scene? I am newish to Godot

Probably using an Autoload is better for what you want to do.

But if you are a new user to the engine, it’s better to start with the Getting Started part of the documentation here Introduction — Godot Engine (stable) documentation in English it will teach you how to use the editor, the concepts of Godot, and how to structure 2 small games one in 2D and another in 3D.

1 Like