Okay here is an example to expand on the question. The player moves their mouse over a parta, but then moves it to partb. How would I keep parta as a viable when the player changes their target?
Right now this is my script which isn't working at all
mouse.Move:Connect(function() if placing then if plr:FindFirstChild("ObjTarget") == nil then objTarg = Instance.new("ObjectValue") objTarg.Value = nil objTarg.Name = "ObjTarget" objTarg.Parent = plr end wait() local mseX = mouse.Hit.X local mseY = mouse.Hit.Y local mseTarget = mouse.Target if mseTarget then for i,v in pairs (tycoon) do if v == mseTarget then unitTarget = v objTarg.Value = unitTarget end end objTarg.Changed:connect(function() previousTarget = mseTarget print(previousTarget) end) end end end)
I am pretty sure I didn't even get close to that script but I have been stumped for the past hour and I'm finally just going to ask.
The short answer is to assign the current target to a previous target variable at the end of the function (but only if the current target is different from the previous target).
You should keep code that you only want to run once outside of event code. For instance, you only need to check if the player has ObjTarget
once. You should never set up an event within another event, as you do with objTarg.Changed
.
--I assume you have a variety of variables defined here --Create objTarget if needed local objTarget = plr:FindFirstChild("ObjTarget") if not objTarget then objTarg = Instance.new("ObjectValue") objTarg.Value = nil objTarg.Name = "ObjTarget" objTarg.Parent = plr end local previousTarget function IsValidTarget(target) -- returns true if the player can target the specified 'target' object for i, v in ipairs(tycoon) do if v == target then return true end end return false end mouse.Move:Connect(function() if not placing then return end -- do nothing if not placing something local mseX = mouse.Hit.X local mseY = mouse.Hit.Y local mseTarget = mouse.Target if mseTarget and IsValidTarget(target) then -- Update objTarget objTarg.Value = mseTarget -- Update previousTarget if mseTarget ~= previousTarget then -- if they are the same then the user has simply moved the mouse a bit and hasn't changed targets, so only update previousTarget if they are different previousTarget = mseTarget end end end) -- TODO: When you set 'placing = true', you probably want to do "previousTarget = nil", too (if not, be sure that 'previousTarget' is set to nil somewhere)
If you need to access previousTarget
outside this script, you'll need to turn it into an ObjectValue just like ObjTarget
.