Not Identifying Instances in Different Functions

I was wondering why a part created in one function can not be recognized by other functions

	local part = Instance.new("Part")
	part.Parent = workspace
	
end

while task.wait(2) do
	part:Destroy()
end

this is just a simple concept script i made but for some reason the part created in the first function is not recognized by the other

Because of Scopes

There is a thread by Roblox which Explains it

Ok so I discovered an extremely hacky fix for this (still make sure to check out the documentation of scopes Cairo linked Not Identifying Instances in Different Functions - #2 by xGOA7x): make a globally scoped variable with any number or string it doesn’t matter then later in your script when you want to make the new instance take that variable and set it to the new instance like this,

testvar = Instance.new("part")

and there you go you have just made a new instance that can be referenced in any function of the script (dont rely on this much cause I figured it out in like 15 minutes and Im not sure what liabilities come with doing this but from my testing it seemed to work just like creating any other new instance)

Edit: this is not actually a hacky fix its just the way the script sees variables and also you dont need to have anything in the variable you can just do this, Not Identifying Instances in Different Functions - #4 by HugeCoolboy2007

That’s not really “hacky”; that’s just how variables work.

Also, you don’t need to assign a value to a variable by default, you can just create it:

local variable; -- creates a variable named "variable" that doesn't have a value assigned to it 
1 Like

Like @HugeCoolboy2007 said, defining a variable outside of a function is not a hacky solution. Variables created inside of functions are not accessible because they are created locally inside that function. By defining the variable before hand, you are allowing both the function and any code outside the function to access that variable.

local GlobalVariable = true --Variables defined on the outside are "global"

function UpdateVar(State1, State2)
	
	GlobalVariable = State1 --Defined before; accessible inside and outside
	local LocalVariable = State2 --Defined inside; only accessible inside
	print (LocalVariable) --Prints true because it was defined in this function
	
end

UpdateVar(false, true)

print(GlobalVariable) --Prints false because it was assigned outside the function
print(LocalVariable) --Throws an error because it was never defined outside the function
1 Like

I am fairly new to scripting so I guess I shouldn’t call things hacky if I dont really know what Im talking about I just thought that it was odd how you had to have a premade variable in order to create new instances that are seen by the rest of the script so thanks for the input.

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