Why isn't cylinder mesh rotation working?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Curiously99

I put some lights and a camera in a 3D scene, then add a secondary 3D node and attach this script to that second node:

extends Node3D

var meshNew = MeshInstance3D.new()
var xAxis = 0.0
var yAxis = 0.0
var zAxis = 0.0
var xRotationDegress = 90
var whileXcount = 0

func _ready() -> void:
	while whileXcount <= 5:
		self.add_child(meshNew.duplicate())
		meshNew.global_position = Vector3(xAxis,yAxis,zAxis)
#		meshNew.global_rotation_degrees.x = xRotationDegress
		meshNew.mesh = CylinderMesh.new()
		meshNew.mesh.top_radius = 0.05
		meshNew.mesh.bottom_radius = 0.05
		meshNew.mesh.material = StandardMaterial3D.new()
		xAxis += 1
		whileXcount += 1

Once I’ve run it I see a row of 5 thin cylinders, all upright. When I remove the hash and run the code with the rotation line, I see the cylinders are all on their sides, as I want, but now they’ve stopped being spaced out in a row - they must all be one on top of the other, because it actually looks like only one cylinder.

Why oh why is this? I’ve racked my brain.

:bust_in_silhouette: Reply From: a_world_of_madness

You are using the meshNew variable during the loop without ever updating it to refer to the next mesh instance.
This should fix the loop:

while whileXcount <= 5:
	var meshNew = MeshInstance3D.new()
	self.add_child(meshNew)

Then remove the the initial meshNew creation outside the loop, otherwise you end up with 5 duplicate cylinders and the original one that’s never added to the scene.

If all the cylinders use the same mesh, you shouldn’t create a new CylinderMesh every time, you can pre-generate the cylinder before the loop and assign it to each MeshInstance. That way they share the same mesh and material and you save memory:

extends Node3D

var xAxis = 0.0
var yAxis = 0.0
var zAxis = 0.0
var xRotationDegress = 90

func _ready() -> void:
	# Generate the shared mesh
	var cylinderMesh = CylinderMesh.new()
	cylinderMesh.top_radius = 0.05
	cylinderMesh.bottom_radius = 0.05
	cylinderMesh.material = StandardMaterial3D.new()
	
	var whileXcount = 0	
	while whileXcount <= 5:
		var meshNew = MeshInstance3D.new()
		self.add_child(meshNew)
		meshNew.global_position = Vector3(xAxis,yAxis,zAxis)
		meshNew.global_rotation_degrees.x = xRotationDegress
		# Use the same mesh for all nodes
		meshNew.mesh = cylinderMesh
		xAxis += 2
		whileXcount += 1