Gameobjects return same position and are different (SOLVED)

I have two game objects with different urls with the same script , In the init I get the spawn pos that is correct on the console log , but appear to get the position off the other gameobject . I want to save the init
position independent of the game object with the same script.

How I can do it?

53

How are you storing the position? Two game objects with the same script can store instance specific variables in the self object.

local initPos = vmath.vector3()
       
function init(self)
    	   initPos = go.get_position()
        end

if canReturnToHand == true then
		local pos = initPos
		go.animate(go.get_id(), "position.x", go.PLAYBACK_ONCE_FORWARD, pos.x, go.EASING_OUTBACK, 0.2)
		go.animate(go.get_id(), "position.y", go.PLAYBACK_ONCE_FORWARD, pos.y, go.EASING_OUTBACK, 0.2) 

This is the way that I use to “store” the init position

You should store on self, not as a local. Local variables outside the lifecycle functions will be shared between instances.

2 Likes

If I replace with self I get this error, How I can get the init pos in a correct way?

attempt to index global 'self' (a nil value)

stack traceback:
/main/main.script:33: in function ‘returnToOrigin’
/main/main.script:76: in function </main/main.script:49>

It sounds like you tried to use it outside of a function. ‘self’ isn’t a global, it is an argument passed in to the functions called by the engine. You just need to do:

function init(self)
    self.initPos = go.get_position()
end

Then you can access it from inside the other basic function (update, on_message, etc.)

2 Likes

But I cannot access in custom functions no? outside the engine by default functions I mean.

1 Like

you can, by passing self as an argument.

local function show(self, other_args) --notice self is an argument
--do something with self
end

function init(self)
    show(self, other_args)     --self passed as an argument
end
5 Likes

Okay thanks, Now I get how its working :slight_smile:

2 Likes