Difference between revisions of "Variables and Properties"

1,022 bytes added ,  17:04, 1 October 2012
→‎Warnings: Attempted to clarify warnings based on feedback from SmkViper
imported>Cipscis
m ("Fixed" headers so highest level is h2)
imported>Cipscis
(→‎Warnings: Attempted to clarify warnings based on feedback from SmkViper)
Line 183: Line 183:


==Warnings==
==Warnings==
Be careful with variables and auto properties on scripts that are extended by other scripts - especially where some script somewhere else may have a property pointing to the base script, or trying to cast to the base script. This is because it would be possible to have two copies of a script attached to the same object, thereby creating two copies of the variable/auto property - and the other scripts that refer to the base script may randomly pick which one to talk to.
Be careful with variables and auto properties on "base" scripts, which are extended by multiple other scripts. This is because it would be possible to have multiple scripts containing the same variable or auto property attached to the same object, and the game may not reliably select the appropriate instance of the variable or property.


This is doubly-true of scripts with native functions, as the game can attach these to in-game objects at any time if it needs to, thereby creating another copy of the variable or auto property.
For example, consider the following 3 short scripts:<source lang="papyrus">ScriptName Base extends ObjectReference
 
Int Property MyValue Auto</source>
<source lang="papyrus">ScriptName Derived1 extends Base</source>
<source lang="papyrus">ScriptName Derived2 extends Base</source>
Because both Derived1 and Derived2 extend Base, they each inherit its MyValue property.
 
Now, imagine that an object is created and the scripts Derived1 and Derived2 are both attached to it. Trying to access the value of MyValue by casting this object to Base will not reliably return the same value:<source lang="papyrus">(MyObjectReference as Base).MyValue</source>
 
This is doubly-true of variables and auto properties declared in [[:Category:Script_Objects|native script objects]], such as the [[Actor Script]]. This is because the game can attach these to in-game objects at any time if it needs to, thereby creating another copy of the variable or auto property.
 
In order to avoid these problems, avoid editing native script objects, and in the case where a single object has multiple scripts attached to it that inherit the same property, make sure you cast it to its most derived form before attempting to access that property. In the above example, that would mean using syntax like this:<source lang="papyrus">(MyObjectReference as Derived1).MyValue</source>


==Notes==
==Notes==
Anonymous user