Complete Example Scripts

From the CreationKit Wiki
Revision as of 11:38, 2 April 2012 by imported>RedwoodElf
Jump to navigation Jump to search

Complete Example Scripts

Script Instantiation

Please remember that few example scripts will be complete by themselves, you must attach a script to an object in the Creation Kit before it will run. The exception is for "library" scripts, such as the Utility Script, which contain definitions of global functions for use in other scripts.

Property Setting

And if the script has any properties, those properties must be set on the object to which the script is attached in the Creation Kit before the script will work correctly.

Script Name

If you use any of these example scripts, you can change the name to anything else, but if you're creating the file outside of the Creation Kit you must make sure it also matches the name of your file.


Scripts

A Quest item you can drop and pick up again and set or reset objectives and Stages.

Scriptname DroppableQuestObject extends ObjectReference

Event OnContainerChanged(ObjectReference NewContainer, ObjectReference OldContainer)
	if FromQuest.GetStage() < StageToStopQuestItem ; Are we a quest item at the current stage?
		if OldContainer == Game.GetPlayer()
			FromQuest.SetObjectiveDisplayed(ObjectiveToDisplayOnDrop,True,True)
			FromQuest.SetObjectiveDisplayed(ObjectiveToHideOnDrop, False) ; Uncomplete the objective completed on pickup.
			if UncompleteEnable
				FromQuest.SetObjectiveCompleted(ObjectiveToCompleteOnPickup,False)
			endif
			if StageToSetOnDrop >= 0
				FromQuest.SetStage(StageToSetOnDrop)
			endif
		elseif NewContainer == Game.GetPlayer()
			FromQuest.SetObjectiveDisplayed(ObjectiveToDisplayOnPickup,True,True)
			FromQuest.SetObjectiveCompleted(ObjectiveToCompleteOnPickup)
			if StageToSetOnPickup >= 0
				FromQuest.SetStage(StageToSetOnPickup)
			endif
		endif
	else ; Nope, we're not a quest item at this stage.

	endif
EndEvent

Quest Property FromQuest  Auto  ; Set this to the quest the item is a quest item for.
Bool Property UncompleteEnable Auto ; If true, "uncomplete" the objective completed on pickup when dropped.
Int Property StageToStopQuestItem = 99999 Auto ; At this stage or later, it effectively ceases to be a quest item anymore.
Int Property StageToSetOnPickup = -1 Auto ; When item is picked up, set this stage in the quest (Defaults to No Stage)
Int Property ObjectiveToDisplayOnPickup Auto ; What objective should be displayed when item is picked up by the player?
Int Property ObjectiveToCompleteOnPickup Auto ; Usually the "Get this item" objective.
Int Property StageToSetOnDrop = -1 Auto  ; If player drops the item, what stage do we "go back" to?
Int Property ObjectiveToDisplayOnDrop  Auto  ; Re-display the objective to "get" the object.
Int Property ObjectiveToHideOnDrop  = -1 Auto ; Should be the same as ObjectiveToDisplayOnPickup, ideally.

To use this script: attach it to the item you want to use, and set the properties accordingly, assigning the quest, Objectives, and Stages involved. For example, let's say that in the quest "StarsAndGarters", the garter belt of Wootazootamootagoota The Tense is set in stage 10 as Objective 10, and Displays Objective 20 "Place the belt on the statue", and sets stage 20 when picked up, and you want to go back to stage 10 if the player drops it. And after stage 30 (Player has put the belt on the statue) it no longer matters what happens to it. You would set your properties as follows:

FromQuest: StarsAndGarters UncompleteEnable: True StageToStopQuestItem: 30 StageToSetOnPickup: 20 StageToSetOnDrop: 10 ObjectiveToDisplayOnPickup: 20 ObjectiveToCompleteOnPickup: 10 ObjectiveToDisplayOnDrop: 10 ObjectiveToHideOnDrop: 20

A Trigger That Detects When The Player Enters

Scriptname ExampleTrigger extends ObjectReference

Event OnTriggerEnter(ObjectReference akActionRef)
	if(akActionRef == Game.GetPlayer()) ; This condition ensures that only the player will trigger this code
		Debug.MessageBox("Yippee!")
	endif
EndEvent

To Make This Script Work

Select an existing object in your cell

Click on the Trigger Volume button, the box with a T inside of it.

  • A orange box should appear around the object you selected.

One reason the Creation Kit is more awesome than any prior editor I've used is this feature!

If you know you need a large trigger volume, select a large object before pressing the T-box button!


  • Now edit the new orange box you created and add the script above.
  • Then go in-game and walk into the space where this invisible box is.

Uses:

  • Create events that depend on player positioning
  • You could eliminate the player if statement above and have other actors like draugr or companions activate things as well
  • Non-player triggers can be used by changing the == to a != in the script above, to do things to other actors like restoring their health or moving them around (but not affecting player if player walks through the trigger)

Cycle Through a List of Objects and Perform an Action on Each Object(FormLists)

This example script cycles through a List of objects, known as a Formlist, and enables them all if they are disabled, and disables them if they are enabled, each time the player character walks through a chosen trigger volume.

If you use a Formlist of special effects, this would cause all the many special effects you have in the formlist to disappear or reappear each time you walk through the trigger volume.

Scriptname RamaFormListExampleScript extends ObjectReference  

;-------- Properties

;--- see notes after script for more info on this property

FormLIST property listOfObjectsFORMLIST auto

;-------- Vars

ObjectReference curRef
int curIndex
int total

;--------

Event onTriggerEnter(ObjectReference objRef)

	if(objRef == game.getplayer())
	
	;--- test index 0 entry to see if all are enabled or disabled
	
	;--- Note that you must typecast the entry from the formlist using "as." 
        ;--- I use ObjectReference so that .isEnabled() becomes accessible. 
        ;--- Use Actor if you want to perform actor functions and the formlist contains actors.

		curRef = (listOfObjectsFORMLIST.getat(0) as ObjectReference)

		;---------------------- Initialize ---------------------
		total = listOfObjectsFORMLIST.GetSize()
		curIndex = 0
		;-------------------------------------------------------

		if(curRef.isEnabled())

			while(curIndex < total)
				curRef = (listOfObjectsFORMLIST.getat(curIndex) as ObjectReference)
				curRef.disable()
				curIndex += 1 
			endWhile

		else

			while(curIndex < total)
				curRef = (listOfObjectsFORMLIST.getat(curIndex) as ObjectReference)
				curRef.enable()
				curIndex += 1 
			endWhile

		endif

		;--------------


	endif

endEvent


To Make This Script Work


  • This script runs on a onTriggerEnter event, so you must create a trigger volume. See the script example above for details on this.


  • Remember to add this example script to the trigger volume object that you create, so you have an actual instance of this script in your level.


  • You must create a formlist of the objects you want to cycle through in this script example.

Formlist making a formlist and populating it.jpg

1. Go to the miscellaneous section of the Object Window and click on formlists,


2. then right click to make a new formlist


3. In your cell view, hold shift and select all of the forms you want to add to the formlist, these could be actors or special effects, activators, or any other kind of form. Name all the forms you want to include from your cell in a similar way so they can be easily selected as a group using shift.


4. Drag the selected forms into the window containing your new formlist information.


5. Make sure to only add forms to your formlist that are all of the same type. Do not mix actors and activators for example.


  • Now you must modify the property of this script example instance, which is present on your trigger volume.

Edit the property so that it points to EditorID of your formlist that you just created.


  • For this script example, I was simply enabling or disabling the objects in the list, so make sure that your formlist contains forms that will react when you enable/disable them. Actors or special effects (look up FX in the *All section of the Object Window) are good forms to start with.


Uses:

  • Any time you have a long list of script properties you want to perform an action on, you can make a formlist instead, and use the while loop to make your coding life Heavenly.


  • Systematically add a certain amount of health or other characteristic to 10 or 2000 actors / creatures to make then stronger or weaker or give them a certain skill (use setAV actor function)


  • Use enable/disable to make a whole bunch of special effect objects (they start with FX in editor) appear or disappear


Enjoy!

Move an Object to a Specific Location Without Fade

You can use this script to make an activator or actor move without fading out in any way (moveTo and setPosition cause fading to occur).

Use this to make objects fly around or make the player move continuously to a destination without fade.


This example moves the player, for your entertainment.


  • To move something other than player, add a property of type ObjectReference and set it to the actor or activator that you want to move (I have not succeeded in moving statics, only activators and actors)
  • Use different Events freely, this event is used for simplicity and easy demonstration.


ScriptName MoveObjExample extends ObjectReference  

ObjectReference property dest auto

Event OnTriggerEnter(ObjectReference akActionRef)

	if (akActionRef == Game.GetPlayer())
		akActionRef.TranslateToRef(dest,500) 
                  ;500 is the speed value, it's pretty fast
	endif

EndEvent

To Make This Script Work

  • Make an XMarkerHeading object (search *All with "xmarker" filter), place it where you want the player to be moved to.
  • Click on an object in your cell and select the Trigger Volume button, the T with a box around it
  • Move the orange box to where you want the player to start their controlled movement to the XMarkerHeading destination.
  • Add this script above to the orange box/trigger volume that you created.
  • SET THE PROPERTY of the script instance, dest, to be your XMarkerHeading that you just made.


This example will not work if you do not set the property as I mention just above, this is an easy thing to forget in this new and wonderful language.

Get used to these basics and you will find Papyrus much more powerful than prior scripting languages.

A Fully Functional Dwemer Button

Scriptname DwemerButtonExampleScript extends ObjectReference  

ObjectReference property objSelf auto hidden
Sound property QSTAstrolabeButtonPressX auto

;==================

;this event runs when cell is loaded containing
;this scripted object

Event OnCellAttach()
	PlayAnimation("Open")
EndEvent

;==================

Event OnActivate(ObjectReference akActionRef)

	if (akActionRef == Game.GetPlayer())

		;--- sound and animation

		PlayAnimationAndWait("Trigger01", "done")
	        if (QSTAstrolabeButtonPressX)
		     QSTAstrolabeButtonPressX.Play(Self)
	        endif

	        ;actual code for what button should do
	        Debug.MessageBox("Joy!")
	
	endif

EndEvent

To Make This Script Work

  • You must create this script on a Activator object, probably a dwemer button :)
  • You must then set the property for the QST sound effect property, the sound file has the same name as the property in the script above.


To make your own dwemer button and avoid messing with the original Skyrim scripts/activators:

  • Extract the dwemer button .nif file from the Meshes.bsa and create a new activator using that .nif file (picking the mesh to use is an option in the activator edit window).
  • You must put your extracted .nif file in the skyrim/Data/meshes directory structure if you want the Creation Kit to be able to find and use it.


To extract files from the Skyirm .BSA files you must download something like the Fallout3 Archive Utility, do a google search for this.


Set Quest Stage When Picked Up By Player

ScriptName SetStageOnPlayerPickUp extends ObjectReference

Quest property QuestToSet auto
int property StageToSet auto

Event OnContainerChanged(ObjectReference akNewContainer, ObjectReference akOldContainer)

	if (akNewContainer == Game.GetPlayer())
		QuestToSet.SetStage(StageToSet)
		GoToState("Taken")
	endif

EndEvent

State Taken
	; Do nothing
EndState


Good Usage of Properties to Make Scripts Compact

In this example you can see how to use a simple script property to reduce the number of scripts you need to write and thus the amount of properties you need to set, which can be time-consuming.


In the example below I was having to do two different things to about 30 different draugrs,

  • turn their AI on and make them visible
  • turn their AI off and make them invisible

I have different conditions within my level for when each of these two actions should occur.


I could divide this into two scripts, but instead I wrote one script and passed a property to the script with each instance of the script to determine which aspect of the script would run.


In this example I only show 3 of the Draugrs I was modifying. Imagine it was 30 Draugrs and you can see why only setting the properties once and writing only one script would be a time-saver :)

Scriptname RamaJRDisableAndMakeInvis extends ObjectReference 

ObjectReference property RamaJRFadeRockArcher001 auto
ObjectReference property RamaJRFadeRockArcher002 auto
ObjectReference property RamaJRFadeRockArcher003 auto

float alpha


;--- The Most Important Line ---
bool property enableBeasts auto
;-------------------------------

ObjectReference curBeast

Event onTriggerEnter(ObjectReference ObjRef)

	if(ObjRef == game.getplayer())

		   if (enableBeasts) ;if enableBeasts is true
                        ;make them visible
                        alpha = 1
                   else
                        ;make them invisible
                        alpha = 0
                   endif

		   curBeast = RamaJRFadeRockArcher001
		   (curBeast as Actor).setAlpha(alpha)
		   (curBeast as Actor).enableAI(enableBeasts)

		   curBeast = RamaJRFadeRockArcher002
		   (curBeast as Actor).setAlpha(alpha)
		   (curBeast as Actor).enableAI(enableBeasts)

		   curBeast = RamaJRFadeRockArcher003
		   (curBeast as Actor).setAlpha(alpha)
		   (curBeast as Actor).enableAI(enableBeast)
		
	endif
endEvent

;// By Kahmul: Added extra script for more readable and shorter code.

Scriptname EnableDisableFast extends ObjectReference

ObjectReference[] Property objAr auto   ; all needed ObjectReferences have to be added here.
ObjectReference curObj

int index

float Property Alpha auto   ; wanted alpha.
bool Property AI auto   ; wanted AI.

Event OnTriggerEnter(ObjectReference player)

	index = 0
	if(player == game.getplayer())
			while(index < (objAr.getlength))
				curObj = objAr[index]
				curObj.setAlpha(alpha)
				curObj.enableAI(AI)
				index += 1
			endwhile
	endif
	
EndEvent

;//End new version.

So notice in the script above, I set the bool as a property value so I can decide with each instance where I run the script which way it should work.


  • Incidentally this script is also a example of casting a variable to a certain type when needed, I cast the ObjectReference to a Actor so I can access the Actor-type functions
ObjectReference curBeast
(curBeast as Actor).enableAI(true)


  • I use curBeast for easy copy-pasting. You could use FormLists to do this process as well


How to Make This Script Work

  • You will need to replace all names for the Draugr Archers (RamaJRFadeRockArcher001 for example) with the exact ID values of each of your chosen creatures.
  • Then you will need to chose for each instance of the script whether the boolean property should be false or true, this setting process shows up a simple checkmark box in the editor

A helper script with functions to get the current moonphase, sync between the two moons and day of the week

Scriptname ExtendedUtility

Import Utility
Import Math

;/++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+
+	GetPassedGameDays() returns the number of fully passed ingame days
+	as int.
+
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++/;

Int Function GetPassedGameDays() Global
	Float GameTime
	Float GameDaysPassed
	
	GameTime = GetCurrentGameTime()
	GameDaysPassed = Floor(GameTime)
	return GameDaysPassed as Int
EndFunction

;/++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+
+	GetPassedGameHours() returns the number of passed ingame hours of
+	the current day as int.
+
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++/;

Int Function GetPassedGameHours() Global
	Float GameTime
	Float GameHoursPassed
	
	GameTime = GetCurrentGameTime()
	GameHoursPassed = Floor((GameTime - Floor(GameTime)) * 24)
	return GameHoursPassed as Int
EndFunction

;/++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+
+	GetCurrentMoonPhase() returns an integer representing the current
+	phase of the moons Masser and Secunda based on "SkyrimClimate".
+	Between 12:00 AM and 11:59 AM the phase during the night from last
+	day to this day is returned. Between 12:00 PM and 11:59 PM the
+	phase for the night from this day to next day is returned. Thus
+	a call to the function at night (between 8:00 PM and 6:00 AM) all-
+	ways returns the currently visible phase.
+
+	The returncodes are as follows:
+		0 - Full Moon
+		1 - Decreasing Moon 3/4
+		2 - Decreasing Moon 1/2
+		3 - Decreasing Moon 1/4
+		4 - New Moon
+		5 - Increasing Moon 1/4
+		6 - Increasing Moon 1/2
+		7 - Increasing Moon 3/4
+
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++/;

Int Function GetCurrentMoonphase() Global
	Int GameDaysPassed
	Int GameHoursPassed
	Int PhaseTest
	GameDaysPassed = GetPassedGameDays()
	GameHoursPassed = GetPassedGameHours()
	
	If (GameHoursPassed >= 12.0)
		GameDaysPassed += 1
	EndIf
	
	PhaseTest = GameDaysPassed % 24 ;A full cycle through the moon phases lasts 24 days
	If (PhaseTest >= 1 && PhaseTest <= 3)
		return 0
	EndIf
	If (PhaseTest >= 4 && PhaseTest <= 6)
		return 1
	EndIf
	If (PhaseTest >= 7 && PhaseTest <= 9)
		return 2
	EndIf
	If (PhaseTest >= 10 && PhaseTest <= 12)
		return 3
	EndIf
	If (PhaseTest >= 13 && PhaseTest <= 15)
		return 4
	EndIf
	If (PhaseTest >= 16 && PhaseTest <= 18)
		return 5
	EndIf
	If (PhaseTest >= 19 && PhaseTest <= 21)
		return 6
	EndIf
	If (PhaseTest >= 22 || PhaseTest == 0)
		return 7
	EndIf
	
EndFunction

;/++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+
+	GetCurrentMoonSync() returns an integer that resembles where we are
+	in the 5 day cycle of the Snychronisation between the moons.
+
+   Returncodes:
+		0 - Moons appear at the same time
+		1 - not yet determined how far ahead/behind Secunda is
+		2 - not yet determined how far ahead/behind Secunda is
+		3 - not yet determined how far ahead/behind Secunda is
+		4 - not yet determined how far ahead/behind Secunda is
+
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++/;

Int Function GetCurrentMoonSync() Global
	Int GameDaysPassed
	Int GameHoursPassed
	Int SyncTest
	
	GameDaysPassed = GetPassedGameDays()
	GameHoursPassed = GetPassedGameHours()
	If (GameHoursPassed >= 12)
		GameDaysPassed += 1
	EndIf
	SyncTest = GameDaysPassed % 5
	return SyncTest
EndFunction

;/++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+
+	GetDayOfWeek() returns the current ingame day of the week as int.
+	
+	Returncodes:
+		0 - Sundas
+		1 - Morndas
+		2 - Tirdas
+		3 - Middas
+		4 - Turdas
+		5 - Fredas
+		6 - Loredas
+
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++/;

Int Function GetDayOfWeek()
	Int GameDaysPassed
	
	GameDaysPassed = GetPassedGameDays()
	return GameDaysPassed % 7
EndFunction

How to make this script work

  • Put it to your "Data/Scripts/Source" Folder and compile.
  • Call it's functions in other scripts either by import and call by function name or by using ExtendedUtility.<FunctionName>()

Script to make an item cast a spell

Scriptname SpellZapScript extends ObjectReference  

import Utility

Float Property xOffset  Auto  
{Relative X position for the target}

Float Property yOffset  Auto  
{Y Offset for Target}

Float Property zOffset  Auto  
{Z offset for Target}

Float Property RandomOffsetX = 0.0 Auto
{Randomness applied to X Offset}

Float Property RandomOffsetY = 0.0 Auto
{Randomness applied to Y Offset}

Float Property RandomOffsetZ = 0.0 Auto
{Randomness applied to Z Offset}

Float Property PulseRate = 1.0 Auto  
{How often do we shoot?}

Float Property RandomRate = 0.0 Auto
{Add random delay to pulse rate, capped at this value}

Activator Property TargetType  Auto  
{What type of object are we zapping if we're spawning a node?}

ObjectReference Property CurrentTarget  Auto  
{The actual target we're shooting at}

Bool Property SpawnNode  Auto  
{Do we spawn a target? If not, zap the nearest valid target.}

Spell Property Zap Auto
{What spell shall we use for the effect?}

FormList Property TargetTypeList Auto
{List of potential targets}

Float Property SeekRange = 1000.0 Auto
{The range it will "Lock into" a target if not making a node.}

Event OnInit()
    if SpawnNode && !CurrentTarget
        CurrentTarget = PlaceAtme(TargetType,1)
        CurrentTarget.MoveTo(Self,XOffSet,YOffSet,ZOffSet)
    endif
    RegisterForSingleUpdate(PulseRate)
EndEvent

Event OnUpdate()
    if !SpawnNode
        CurrentTarget = Game.FindClosestReferenceOfAnyTypeInListfromRef(TargetTypeList,Self,SeekRange) 
	; find something nearby to shoot at if we're not making our own target.
	if !TargetTypeList && GetDistance(Player) < SeekRange ; No list given, Default to the player.
		CurrentTarget = Game.GetPlayer()
	endif
    else
        CurrentTarget.MoveTo(Self, XOffSet+(RandomFloat(0.0,RandomOffsetX)-RandomOffsetX/2 ), \
            YOffSet+(RandomFloat(0.0,RandomOffsetY)-RandomOffsetY/2), \
            ZOffSet+(RandomFloat(0.0,RandomOffsetZ)-RandomOffsetZ/2))
    endif
    Zap.Cast(Self,CurrentTarget)
    RegisterForSingleUpdate(PulseRate+RandomFloat(0.0,RandomRate))
EndEvent

How to make this script work:

  • Put it on the object you want the spells to originate from, and set the properties to define it's exact desired behavior.
  • Pick any spell you want for the property Zap (needs to be of the Aimed spell type)
  • If you want it to just shoot at a specific spot, define the Spawn Node Type as an xmarker, set SpawnNode to "True", and enter the relative coordinates you want the spell to be aimed at.
  • If you want it to look for targets nearby, set SpawnNode to false and put a formlist of the valid targets in the TargetTypeList. If no Formlist is given, it will default to trying to shoot the player.