2017-02-11 14 views
2

我想改變一個部分的顏色,當一個玩家站在它上面,而不是把腳本放在部分內部時,我可以把腳本放在工作區中,並從一個事件中識別部分,比如人形點什麼?當一名球員站在Roblox的一個街區時,什麼事情會發生?

原因是我有100個零件需要對觸摸事件作出反應,所以我不想在每個零件中放置相同的腳本。

僞代碼可能是

球員觸控區域觸發的事件 從事件中標識的一部分,改變部分顏色

感謝

回答

1

爲M. Ziegenhorn寫道,你可以把這個腳本在字符或直接在腳下。這將是實現這一目標的「最簡單」方式。

但是,你可能也容易連接到每個部分的功能。 在下面的代碼中,我們檢查名爲'TouchParts'的工作區中的模型,該模型(假設)包含您想要將觸摸功能綁定到的部分。

function Touched(self, Hit) 
    if Hit and Hit.Parent and Hit.Parent:FindFirstChildOfClass'Humanoid' then 
    -- We know it's a character (or NPC) since it contains a Humanoid 
    -- Do your stuff here 
    print(Hit.Parent.Name, 'hit the brick', self:GetFullName()) 
    self.BrickColor = BrickColor.new('Bright red') 
    end 
end 

for _, object in pairs(workspace.TouchParts:GetChildren()) do 
    if object:IsA'BasePart' then 
    object.Touched:connect(function(Hit) 
     Touched(object, Hit) 
     end) 
    end 
end 

這樣做,這樣意味着你的性格觸摸部(S)什麼會觸發觸摸事件,所以你將不得不在一個檢查添加,看時是否扎系部感人的是腿或不。

將功能綁定到每個部件而不是腿上的優點是,只有當您實際觸摸其中一個預期部件時纔會調用該功能,而不是觸摸任何部件。但是,隨着連接的零件數量的增加,事件數量也會增加,這些事件將被觸發並存儲在內存中。在你所使用的規模上可能不太明顯,但值得記住。

+0

謝謝這是偉大的Ravenshield!觸摸功能中的另一個快速問題我有Hit,它允許我訪問播放器,但是如何在該功能中訪問被觸摸的部分本身?例如,如果我想改變被觸摸的部分的顏色。 – tartangear

+0

使用循環和產生新線程會更高效。 – warspyking

+0

@tartangear我們可以在功能上混合一點。將另一個參數添加到觸摸的函數(例如:觸摸(Hit,Object)),然後爲該事件創建一個匿名函數。這樣我們可以調用Touched函數並傳遞對象。 我編輯了我原來的帖子來解決這個問題。看看它。 – Ravenshield

0

因爲我在roblox上編寫了一些代碼,所以請原諒我犯的任何錯誤。

local parent = workspace.Model --This is the model that contains all of that parts you are checking. 
local deb = 5 --Simple debounce variable, it's the minimum wait time in between event fires, in seconds. 
local col = BrickColor.new("White") --The color you want to change them to once touched. 

for _,object in next,parent:GetChildren() do --Set up an event for each object 
    if object:IsA("BasePart") then --Make sure it's some sort of part 
     spawn(function() --Create a new thread for the event so that it can run separately and not yield our code 
      while true do --Create infinite loop so event can fire multiple times 
       local hit = object.Touched:wait() --Waits for the object to be touched and assigns what touched it to the variable hit 
       local player = game.Players:GetPlayerFromCharacter(hit.Parent) --Either finds the player, or nil 
       if player then --If it was indeed a player that touched it 
        object.BrickColor = BrickColor.new(col) --Change color; note this is also where any other code that should run on touch should go. 
       end 
       wait(deb) --Wait for debounce 
      end 
     end) 
    end 
end 

這可能是最有效的方法之一。

+0

感謝warspyking,我會試試這個。產卵函數很有趣 - 我需要對此做更多的研究! – tartangear

+0

它只是產生一個新的線程。 – warspyking

+0

因此,如果我在模型中有100個藝術,那麼這將在同一時間調用100個線程,這是很多要運行? – tartangear

相關問題