Replies: 17 (Who?), Viewed: 3830 times.
Virtual gardener
staff: administrator
Original Poster
#1 Old 6th Feb 2020 at 9:01 PM Last edited by Lyralei : 13th Apr 2020 at 2:45 PM.
Default The cave of the code snippets!
The sims 3, it's a bit of a confusing... thing when you first start making a script mod for it. What the hell is the difference between "Sim" and "SimDescription"? Or "What was the code again for a simple notification? *scrolls massively*". That's basically how the idea was created between Zoeoe and me. So most of the credits go to her too, for the creation of this thread!
Well, this thread will have covered with simple snippets as to what and when to use something, so both advanced, as well as beginners, can enjoy from it! Or even if you have any questions if EA's code simply allows something or you need an extra push into that coding error!

I've got some good ones to include! 
Make sure to list yours in such a way as shown below. Just so that everything is more organised and easier to find. If you've got an alternative way or even an easier way of doing a particular function, then it's totally fine to share this too, but preferably label these as "Alternative:" or "My way:" Or something like that

Make sure however, not to copy paste your entire script or class. A simple function is fine though!

What this thread isn't for:
This is not a thread about how to fix your code or errors. If there's any errors you encounter and you need help, make sure to create a thread to ask that particular question. Your reply will get deleted/moved as a new thread. Of course, exceptions are for if any snippets happen to have a spelling mistake and it needs to be pointed out 

This thread is also not about asking questions 



Snippet time!

NOTIFICATIONS:



All the notification Styles:
kSimTalking
kSystemMessage
kGameMessagePositive
kGameMessageNegative
kDebugAlert
kCustom
kCelebrityUpdate
Advertisement
Staff - Moderator
staff: moderator
#2 Old 29th Dec 2019 at 7:19 PM
Set game speed:


Adding an alarm to an object:


Remove an alarm on an object:



Check if sim is in active household:


Modify sim's household funds:


Add to sim's household bills:


Destroy an object in the game:
Field Researcher
#3 Old 8th Feb 2020 at 9:12 PM Last edited by Battery : 8th Mar 2020 at 10:10 PM.
If you need to need to get a translation Key directly from the game (for Resourceallergics like myself) you can use this


If you need to Run an Action so that it doesnt block the main thread you can use this

thats all im willing to share for now (thats actually more than i originally wanted to share), since i still need to sell my Script Utility Mod where these snippets are from, to some unsuspecting Modders.. and i did post a whole class. lets see if Lyralei notices
Field Researcher
#4 Old 16th Feb 2020 at 4:22 PM
Enable Extension Methods in SharpDevelop
Virtual gardener
staff: administrator
Original Poster
#5 Old 5th Mar 2020 at 10:45 AM
Standard Statemachine setup, which you can use in run():

Virtual gardener
staff: administrator
Original Poster
#6 Old 12th Apr 2020 at 1:18 PM Last edited by Lyralei : 18th Apr 2020 at 11:44 AM.
Make item stackable in inventory, this is also EA's default way of doing this:


Making the object an inventory-enabled (aka, being able to be stored in inventories)



Available types you can use for this:
  • Sim
  • SharedFamilyInventory
  • Your own Custom object that has an inventory (Make sure this is the first class of your script, so not the interaction classes)
  • Tomb chests, EA's inventory objects (Even the InventionBench if you like! )
Making object draggable from a code perspective:


Virtual gardener
staff: administrator
Original Poster
#7 Old 3rd May 2020 at 1:13 PM
A snippet that makes it easier to figure out how long it took to load a function, loop, method, or anything alike. (Credits to Tashiketh as well).


Usually, you'd use the StopWatch class for it. Unfortunately, EA took that out of their own System.Diagnostics version :/. So this is just a simple workaround! If you want to check multiple, then just do exactly the same repeatedly.
Field Researcher
#8 Old 3rd May 2020 at 6:05 PM Last edited by gamefreak130 : 3rd May 2020 at 6:17 PM.
Quote:
Originally Posted by Lyralei
A snippet that makes it easier to figure out how long it took to load a function, loop, method, or anything alike. (Credits to Tashiketh as well).


Usually, you'd use the StopWatch class for it. Unfortunately, EA took that out of their own System.Diagnostics version :/. So this is just a simple workaround! If you want to check multiple, then just do exactly the same repeatedly.


StopWatch was taken out of System.Diagnostics because EA implemented their own StopWatch class in SimIFace.

Basic functionality is pretty much the same as the System StopWatch. Here's an example:

Code:
using Sims3.SimIFace;
using Sims3.UI;

internal void TimedProcedure()
{
    StopWatch timer = StopWatch.Create(StopWatch.TickStyles.Microseconds).Start();
    // Things
    // TODO More things
    // Optional: Maybe some more things here?
    timer.Stop();
    SimpleMessageDialogue.Show("TimedProcedure() took " + timer.GetElapsedTimeFloat().ToString() + " microseconds to execute.");
    timer.Dispose();
}

"The Internet is the first thing that humanity has built that humanity doesn't understand, the largest experiment in anarchy that we have ever had." - Eric Schmidt

If you enjoy the mods I put out, consider supporting me on patreon: www.patreon.com/Gamefreak130
Staff - Moderator
staff: moderator
#9 Old 17th May 2020 at 3:58 PM Last edited by zoe22 : 20th Oct 2020 at 8:05 PM.
Greyed out message for when you cannot do an interaction for some reason (in Test function of InteractionDefinition):

Field Researcher
#10 Old 7th Jul 2020 at 5:44 AM
This is a cleaned-up repost from another discussion thread.

All interactions in the game have a priority level assigned to them. When the game adds an interaction to a Sim's queue, all lower-priority interactions already in the queue are automatically canceled. Most interactions share the same default priority, but certain interactions (mainly reactions to burglars, mummies, simbots, etc.) are labeled by the game as high priority, meaning they will rather annoyingly cancel all user-directed interactions in the queue when they are assigned. If you want to work around this for a custom interaction (or make an interaction with the same functionality), you'll need to make it high priority by adding the following to your interaction's class:

Code:
using Sims3.Gameplay.Interactions;

public override void Init(ref InteractionInstanceParameters parameters)
{
    parameters.Priority = new InteractionPriority(InteractionPriorityLevel.High);
    base.Init(ref parameters);
}


There are priority levels higher than high, but they shouldn't be used unless you know what you're doing.

As an aside, if at any point in an interaction's Run() method you want it to become uncancellable (i.e. the user can't click to remove it from the queue), you can use the following property of InteractionInstance:

Code:
CancellableByPlayer = false;

"The Internet is the first thing that humanity has built that humanity doesn't understand, the largest experiment in anarchy that we have ever had." - Eric Schmidt

If you enjoy the mods I put out, consider supporting me on patreon: www.patreon.com/Gamefreak130
Virtual gardener
staff: administrator
Original Poster
#11 Old 18th Aug 2020 at 9:57 AM
Whenever your function happens to be somewhat heavy on the game, this method can help (Credits to gamefreak130 as well)

Code:
public override bool Run()
{
   // when adding the function, never add the () to the end. This is because it expects a delegate
   Simulator.AddObject(new OneShotFunctionTask(new Function(yourFunctionhere)));
}
public void yourFunctionhere() 
{
   // code you want to fire here.
} 
What it does, is it fires the function on a different thread whenever it can, meaning that there's less pressure onto the game for running said function. This function is an asynchronous function, as it waits till the game is ready to fire it on a different thread.  This is defined with using OneShotFunctionTask. Function, of course, just defines which function it should look at.

Simulator.AddObject(), just adds this function for the simulator's 'todo list' so to speak.  (The simulator is the system that also has sims do stuff automatically, etc)

There is a way to parse any needed parameters for the function, but that I've never gotten to work beside a whole workaround. So I'd recommend keeping your function within the interaction bit you're using this in. So under the Run() function if you will
Field Researcher
#12 Old 11th Oct 2020 at 9:27 PM Last edited by gamefreak130 : 12th Oct 2020 at 3:02 AM.
This is by no means a "snippet", but I just over-engineered a thing that I wanted to post here.

PersistableStatic fields are very useful for pure script mods, since they can effectively serve as global variables whose values can be tied to a save game and automatically saved/loaded by the game. However, multiple worlds in a single save will maintain separate copies of these fields, and their current value will automatically become the default starting values in newly-exposed worlds. When you travel to China, attend university, start a new game after quitting to main menu, etc., the value of PersistableStatics at the time of world loading will be carried over, but any further changes in one world will not affect the values in another. This is useful in some situations (e.g. keeping track of the number of Sims in a world), but not in others (e.g. keeping track of how many sim-days have been simulated save-wide).

To work around this, I created a generic static class (an obscure feature of C#, but a helpful one in this case) that can "ferry" any PersistableStatic data declared in a class or struct across worlds when traveling, effectively allowing an entire save to share a single copy.








"The Internet is the first thing that humanity has built that humanity doesn't understand, the largest experiment in anarchy that we have ever had." - Eric Schmidt

If you enjoy the mods I put out, consider supporting me on patreon: www.patreon.com/Gamefreak130
Staff - Moderator
staff: moderator
#13 Old 13th Dec 2020 at 2:05 PM
Replacing an existing interaction - Should go in OnPreLoad() NOT OnWorldLoadFinished()(Thanks to Battery for this one ):


Count number of objects on a lot:


Get List of certain type of object in an Inventory:


Route to an object's general area:


Create an object:
Virtual gardener
staff: administrator
Original Poster
#14 Old 10th Jan 2021 at 3:29 PM
Not a code snippet, since it's a pretty big code snippet by itself, so here's the link: https://www.modthesims.info/showthr...375#post5703375

This code snippet shows how to change the name of an object to rename the object's name. The name component is basically the functionality how we can name a sim's car whenever they're best friends with their car
Virtual gardener
staff: administrator DELETED POST
Original Poster
5th Feb 2021 at 6:14 PM
This message has been deleted by Lyralei. Reason: Not really necessary
Virtual gardener
staff: administrator
Original Poster
#15 Old 27th Feb 2021 at 12:57 PM
Try and catch method to figure out why your jazz script doesn't work
If your jazz script is not working as expected, you can use EA's debugging exceptions to catch it



Solo animations for testing
If you want to play just an animation without wanting to make a jazz script, or you want to check if your CLIP animation works before making a jazz script, you can also use:

Test Subject
#16 Old 12th Mar 2021 at 10:07 PM
From The Depths of The Sim State Mines...
Hi so as a new script modder and working on my Sim State mod for a while I decided (after many...MANY prods :P) to post about my findings that might be useful in a snippet type format. Hopefully I don't cover what has already been said I'm trying to do unique ones .

Query Objects Of a Certain Type
-Finds objects of that type either in general or a specific lot. - Can be GameObject, Sim, or a specific object within the world. Add a 'LOT' inbetween the () to narrow the search to particular lot.
Code:
Computer[] computer = Queries.GetObjects<Computer>();


Get Interaction Type
-Find whether an object has a specific interaction type, so for example if you created an interaction class called 'StartBusiness' (off the top of my head :P) you would do the following:
Code:
foreach (InteractionObjectPair interaction in computer.Interactions)
{
                if (interaction.InteractionDefinition.GetType() == StartBusiness.Singleton.GetType())
	        {
                        //DO CODE HERE... LIKE REMOVE INTERACTION ETC.
                }
}


Get Object By Unique ID
-All objects in a world are unique so if you want to find out information about a set object you can do the following:
Code:
GameObject.GetObject(objectID).theMethodYouWantToCall;


Find An 'Actors'/Sims Traits
-Check the basic pure script tutorial to find out the difference between Actors & Targets (I.E Sims & their Interaction Objects (another sim, object etc)).
-The trait names will list if you just press the . and then you can choose from a list of all the available traits in the game!
Code:
//Within an interaction.
actor.TraitManager.HasElement(TraitNames.Good)
//Actively selected sim:
Sim.ActiveActor.TraitManager.HasElement(TraitNames.Good)


Household IDs
-You can check for the unique household ID of an active sim, or actor which you can query if storing data about that 'household':
Code:
Sim.ActiveActor.Household.HouseholdId;


Playing A Default EA Sound Effect
-You can find the strings by searching through ILSPY (and perhaps another way but I'm not sure), but for example below this will play the career promotion sound effect, but is used to play any sound. Keep in mind however most sound playback does checks to see if another sound is playing etc.
Code:
Audio.StartSound("sting_career_positive");


Removing An Interaction (By Type)
-Similar to the get type method above, you can also remove an interaction from an object that you have queried within a for/foreach: (Will remove SetForSale Interaction or whatever one you want!).
Code:
obj.RemoveInteractionByType(SetForSale.Singleton);


Persistable Data - Saving Your Stuff With EAs Code
-So if you're making anything more than a one shot kind of mod you're going to want to save data. Logically while the game is open anything you have stored in variables through the code will be saved but you need to explicitly save it along with The Sims 3 code base. Not 100% of exactly how this works but in short you can do the following above a class you wish to preserve:
Code:
[Persistable]
//Or if its static data:
[PersistableStatic]
//Add the following to your assemblyinfo.cs file at the end of the other [] options:
[PersistableStatic]
//Thats it... you don't need to open a file or do any of that, basically what persisting does it literally 'freezes' the state of the variables stored when the game is saved by the user via the save button. You can then add anything you wish to save in some kind of 'save' class. If you are using a class however and you have a constructor with parameters, you need to make sure you have one empty constructor above the used one. Not sure why.. ask GameFreak lol but it won't work properly without this. Example:
public class Save_Test
{
          Save_Test()
          {
          }

          Save_Test(ulong lotID, int simName)
          {
          }
}


Nested Pie Menu Options (The Real Estate... kind of ones)
-If you have a lot of interactions then you wont want to clutter up the object you're adding to so you can nest them, see the real estate option on the phone or computer for this example. In short it will add any interaction you add the 'path' too, under that path. Put the code in the interaction class, WITHIN the definition class, which contains the GetInteractionName & Test functions/methods.

Code:
public override string[] GetPath(bool isFemale)
{
	return new string[1] {"Real Estate..."};
}


Changing An 'InWorld' Objects Price
-At times you may want to adjust the price of a placed ingame item, for example I wanted 'bought' items from my business mod to be set to $0 until restocked, so they were basically worth nothing. Its VERY easy. This example uses a referenced object under an interaction but would work the same with any object queried too as you get access to the same list of methods :
Code:
base.Target.mIntPrice = 0;


Changing An Objects Color
-A little tempremental but in short the following code will 'tint' your objects a color, I haven't tested but in short it seems to work on a 0-100 basis. 100 being full color. The parameters are (r,g,b,transitiontime). Example:
Code:

//Will tint the object in question to red!
base.Target.SetColorTint(100f,0f,0f,0f);


Adding Moodlets to A Sim/Actor
-Simple really, you can add any moodlet in the game to a Sim with the following, and set its origin and length of time to show!
Code:

//BuffNames (press . to see a list of ALL moodlets (buffs) in the game!). MoodAxis affects the mood of the Sim but I don't remember exaxctly what it does... has options similar to The Sims 4 emotions! The origin gives another drop down with a list of potential options as to where the Sim got the moodlet from as they hover over it. The 60f bit is in 'sim seconds' so 60f would be 1 real life minute. The f bit refers to 'float' or basically decimal numbers, but you don't need to add a decimal it works fine with whole / integers.
base.Actor.BuffManager.AddBuff(BuffNames.NewStuff, 0, 60f, false, MoodAxis.Fulfilled, Origin.FromNewObjects, false);


Find A Household By ID
-At times if you are storing the household ID to reference you may wish to find that household to manipulate various options you can do that with the following code:
Code:

//The modify family funds bit will adjust the amount of money + or - depending on the value entered. You can just press the . after the find() method though to see a list of all options to perform on households anyhow .
Household.Find(householdID).ModifyFamilyFunds();


Visual Effects!
-Okay so this is early days I don't know EXACTLY how this works but I feel confident that if you just change the name of the visual effect it would play automatically on any target (sim/object etc).
Code:

//Change the name of the effect in the " " to show different effects when an interaction is run on your object. The one shown here will show the 'simoleon fly out' effect from the store savvy seller set! Just copy/paste into your code to do the same. Let me know if you understand more than me on this one .
VisualEffect visualEffect = VisualEffect.Create("store_rugPurchase");
Vector3 trans = Vector3.Zero;
Vector3 axis = Vector3.Zero;
if (Slots.AttachToBone(visualEffect.ObjectId, Target.ObjectId, ResourceUtils.HashString32("transformBone"),false,ref trans, ref axis, 0f) == TransformParentingReturnCode.Success)
{
visualEffect.SetAutoDestroy(destroy: true);
visualEffect.Start();
}
else
{
visualEffect.Dispose();
}


Move A Sim To An Object Radius and Check If In Use
-This one is easy as it says it in the method name lol:
Code:

//Use within an interaction or on a 'Sim' directly. base.Target is the object/sim to route too, and the 0.5f, 2f is the radius, i'm not sure what this is measured in but this seems to get the sim 'close' to an object as I found it in Ani's code so it works! It will also check if another Sim is using the object, for example it will 'return' false if a sim is sat in a chair its referencing.
base.Actor.RouteToObjectRadialRangeAndCheckInUse(base.Target, 0.5f, 2f)


Numbers In A String Dialogue
-At times you want user input but not always just a sting (or text), so you can do the following to ask for numbers ONLY and then convert the users text into an 'int' for using elsewhere:
Code:

//The 'true' bit at the end is whether you want to allow ONLY numbers, if false you can take letters like usual. The result after the user presses the 'tick' button is stored in the variable name after 'string'.
string newCost = StringInputDialog.Show("Change Cost","Choose how much this object will cost:","",true);
int result;
//Here it just says 'try turn the string newCost into a number' and if successful return it in the previously declared 'result' variable!
int.TryParse(newCost, out result);


That's all for now, there are a few other things I could post about but need a break, hope this helps someone! And turns down the volume on requests for me to do it finally haha.

Thanks!

SSD.

Creating Sim State Expansion for The Sims 3. :)
Instructor
#17 Old 3rd Apr 2021 at 4:22 AM Last edited by echoweaver : 12th May 2021 at 2:49 PM.
Add an Inventory Interaction

This is when you want an interaction to show up when you click an item in inventory. Obvious to look at, but I had to dig to find an example .

Code:
item.AddInventoryInteraction(InteractionClass.Singleton);


Inventory interactions use RunFromInventory() instead of Run()

To check whether an inventory interaction has already been added to an object, use:

Code:
foreach (InteractionObjectPair pair in object.GetAllInventoryInteractionsForActor(sim))
{
   if (pair.InteractionDefinition.GetType() == InteractionYouWant.Singleton.GetType())
   {
      return;
   }
}

Echo Weaver's Simblr: http://echoweaver.tumblr.com/
A portrait in stubbornness - Playing the same legacy since 2009
Sample a Brave Legacy: http://sims3sample.illation.net
Instructor
#18 Old 12th May 2021 at 2:45 PM
To put up a pick list to let the user select from a group of objects using their name, you can use ObjectListPickerDialog.

Pickers are kind of weird -- you don't have to instantiate them. Just call the static Show() method, and they'll instantiate themselves and pop up to the user. This is the simplest picker subclass I've found, and it's the only one I've needed to use so far. Its Show method takes a parameter of type List<ObjectListPickerInfo>. ObjectListPickerInfo is just a class of two items: a string name and an object.

Here's an example that will pop up a picker asking the user to select a pet breed by its name (e.g. "Dalmation"). The picker returns the BreedOutfit object containing all the info about the breed.

Code:
List<BreedOutfit> mBreeds = CASLogic.GetBreedOutfitList(speciesFlag);
List<ObjectListPickerInfo> breedInfo = new List<ObjectListPickerInfo>();

foreach (BreedOutfit b in mBreeds)
{
   ObjectListPickerInfo o = new ObjectListPickerInfo(StringTable.GetLocalizedString(b.BreedLocKey), b);
   breedInfo.Add(o);
}
return ObjectListPickerDialog.Show(breedInfo) as BreedOutfit;

Echo Weaver's Simblr: http://echoweaver.tumblr.com/
A portrait in stubbornness - Playing the same legacy since 2009
Sample a Brave Legacy: http://sims3sample.illation.net
Back to top