I’m using a specific game making framework but I think the question applies to javascript
I was trying to make a narration script so the player can see “The orc hits you.” at the bottom of his screen. I wanted to show the last 4 messages at one time and possibly allow the player to look back to see 30-50 messages in a log if they want. To do this I set up and object and an array to push the objects into.
So I set up some variables like this initially…
servermessage: {"color1":"yellow", "color2":"white", "message1":"", "message2":""},
servermessagelist: new Array(),
and when I use this command (below) multiple times with different data called by an event by manipulating servermessage.color1 … .message1 etc…
servermessagelist.push(servermessage)
it overwrites the entire array with copies of that data… any idea why or what I can do about it.
So if I push color1 “RED” and message1 “Rover”.. the data is correct then if I push
color1″yellow” and message1 “Bus” the data is two copies of .color1:”yellow” .message1:”Bus”
When you push
servermessageintoservermessagelistyou’re really (more or less) pushing a reference to that object. So any changes made toservermessageare reflected everywhere you have a reference to it. It sounds like what you want to do is push a clone of the object into the list.Declare a function as follows:
Then everytime you want to push a message into the list do: