|
One of the most difficult aspects of handling dynamic sprites is working with the scriptInstanceList to attach behaviours at runtime.
Because of this, I wrote the following function to attach behaviours at runtime, so that they work exactly as if they were attached by the score at design time. You do not need to modify the behaviour code (as recommended in a prior Usenet post). The function even takes care of getPropertyDescriptionList parameters.
Usage examples:
addScriptToSprite( sprite(10), "My Behaviour" )
addScriptToSprite( 10, "My Behaviour", [#myProp: 15] )
Note that the third parameter, which is optional, allows you to override the default values in the behaviour properties dialog, if there is one.
It does not allow you to override any old properties, the reason being that the values are inserted before the behaviour's new() and beginSprite() handlers are called. This is for maximum compatability, as it is possible that a behaviour might rely on one or more properties having their default value of VOID during initialisation.
If you want to override any other properties, you should do it *after* the script has been created by the function, and attached to the sprite. Here's an example of that:
theScript = addScriptToSprite( 10, "My Behaviour" )
if( ilk( theScript, #symbol ) ) then
-- The call failed for some reason
else
theScript.myProp = 15
end if
The above example also shows how to check for an error code. However, you will almost never need to check for errors, as long as you are sure that the sprite number (or reference) passed to the function is correct. If there is any possibility that this may not be correct then you should check for errors, but in practise such a situation is unlikely to arise.
One final thing to bear in mind is that this function does not help clear the scriptInstanceList when you jump to another frame.
When you modify the scriptInstanceList of a sprite you need to set it to [] when you are done, then un-puppet the sprite. You can get weird effects if you forget about this, because any behaviours you attach will remain attached to the sprite channel throughout the whole movie.
Warning
Never modify the scriptInstanceList of a sprite from a behaviour attached to the same sprite. For example:
on mouseUp me
addScriptToSprite( me.spriteNum, "Another Behaviour" )
end
on rightMouseUp me
sprite( me.spriteNum ).scriptInstanceList = []
end
These examples are WRONG. They will cause unpredictable results because Director is already using the scriptInstanceList to process your behaviour. If you modify the list at that time then Director will get confused - this can cause anything from incorrect behaviour to memory leakage (which can lead to your movie, or whole PC, crashing).
Source Code

|