Access variable after pre-loading node from another script (C#!)

Godot Version



Hello, I am stuck with C#… well what am I need to do when I want to access variable from another script inside different PackedScene? I was trying to google all of that but I only found ez solutions for GDscript (I really don’t want to use GD).

// This scene stores variable named "Active" but even you add it to the tree you can't access it like in GD script...
var projectile = ResourceLoader.Load("res://lol/projectile.tscn")                                                       as PackedScene;
// This node is place where projectile is added as child node.
var spawn_node = GetNode(WeaponViewport.GetPath().ToString() + "/Camera/Root/" + CurrentWeaponDir + "/ProjectileSpawn") as Marker3D;
// Point where projectile will land.
var raycast    = GetNode(WeaponViewport.GetPath().ToString() + "/Camera/RayCast")                                       as RayCast3D;

// Adding projectile to spawn_node. 
var x = projectile.Instantiate() as RigidBody3D;

// Thats what I am trying to do... just set bool to true in other node/script created from PackedScene.
x.Active = true

I appreciate any help.

Not really sure, but maybe could cast it as a projectile instead:

var x = projectile.Instantiate() as Projectile;

Or whatever you named your script for the projectile scene.
Also, Active must not be private to be accessible from another script.


This is a tangent (ronald’s explanation is correct), but in C# there are also a coupled PackedScene extensions the docs don’t cover afaik.

.Instantiate<T>() and .InstantiateOrNull<T>()

The first will cast to your type and throw an InvalidCastException if unable. The second is equivalent to .Instantiate() as T

I personally prefer to use the first one by default, and only use the other approaches if I’m not strictly controlling the source type for some reason. In your example, if for some reason the PackedScene you load isn’t the type you expected, instead of getting a cast exception you’ll get a null reference exception when you try to use the object.

This isn’t to say you shouldn’t write it that way; there are just tradeoffs and different error-handling approaches.

1 Like

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