How do I access variables from an instanced scene with code?

Godot Version

v4.2.1.stable.official [b09f793f5]


I’m making a breakout clone as practice and getting used to the Godot engine.

Basically when i hit “powerup 3” with my ball I want to duplicate the ball so 2 balls are bouncing around

The problem is that I throw an error with the ball.state = state line of code.

“Invalid set index ‘state’ (on base: ‘CharacterBody3D’) with value of type ‘int’.”

The ball is properly created and the velocity code works but no dice on the variable. How do i fix? Thanks! Code is below.

var extra_ball = preload("res://ball.tscn")
if brick.powerup == 3: #BALL
	var ball = extra_ball.instantiate()
	ball.state = state             #this doesn't work
	ball.velocity = Vector3.FORWARD * speed          #this does
1 Like

I had a similar problem before, try to change the order, put add_sibling(ball) at the end.

Thanks for the response!

I actually originally had it in that order and had the same error occur. A different post i saw suggested adding the scene first then altering the var but in my case it doesn’t seem to matter.

I think its about other things, what is state in ball?, and what are you putting inside it in this function?

ball.state = state is just assigning the new ball to the current ball’s moving state which has movement and collision code. I don’t think anything in the state is the issue.

state is just a var with an integer
“state = 1”

I am facing the similar problem, please give the solution.

OK, so below is the new code that seems to make it work as intended. A few things:

First - My script that the code lies in was on the ball Node in my main scene. There was no script attached to the root node of the ball scene i instantiated. So i attached the same script to that. This did not work and gave the same error, even though the variable “state” was in that script. I’m still not sure why this didn’t work.

Second - I ended up making a variable to store the script to preload it right away. Then i instanciated the ball scene and added the script to it in code. This worked. I tried adding the script to it before in code but i think the big difference was preloading the script.

Thanks for the help all!

Here’s the modified code:

preload scene and script

var extra_ball = preload("res://ball.tscn").instantiate()
var ball_script = preload("res://")

add ball if getting powerup 3

if brick.powerup == 3: #BALL
	extra_ball.state = state
	extra_ball.velocity = Vector3.FORWARD * speed
1 Like

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