Introduction to Scripting

Your First Interactive Object - Learn the fundamentals of LSL scripting and bring your creations to life with interactive behaviors.


Course Code
SCR-301

Level
Intermediate

Duration
3-4 Hours

Certificate
Available

Lead Instructor

Sorin Todys - Advanced LSL Expert

With over 20 years of experience in virtual worlds, Sorin specializes in making complex scripting concepts accessible to beginners. All classes take place at our dedicated Alife Virtual School region.

Course Overview

Welcome to the exciting world of LSL scripting! This course transforms you from a builder of static objects into a creator of interactive experiences.

What You'll Learn

  • Fundamental structure of LSL scripts (states, events, functions)
  • Using the in-world script editor effectively
  • Making objects respond to touch interactions
  • Controlling object properties (color, text, light)
  • Detecting and personalizing interactions with avatars
  • Creating state machines for complex behaviors
  • Debugging and troubleshooting scripts

Learning Objectives

Upon completion, you will be able to:

  • Write and edit LSL scripts confidently
  • Implement touch-based interactivity
  • Use variables and data types correctly
  • Create multi-state objects (like light switches)
  • Personalize object responses to different users
  • Debug common scripting errors
Prerequisites: Basic building skills required. You should be comfortable creating prims, moving objects, and accessing edit menus. We recommend completing BLD-101: Building Fundamentals first.

Lesson 1: The Magic of "Hello, World!"

Understanding Scripts

A script is a set of instructions that lives inside an object and controls its behavior. Think of it as the "brain" that gives your creation intelligence and interactivity.

Key Concepts

Event-Driven Programming

Scripts wait for events to happen (like touches, timers, or messages), then execute the appropriate response code.

Script Structure

Every script has states that contain events which execute functions.

The Three Pillars of LSL

1. States

A script is always in a specific state. The starting state is always called default. States help organize complex behaviors.

default  // This is a state
{
    // Events go here
}
2. Events

Events are triggers that cause code to execute. Common examples:

  • state_entry() - Runs when script starts or resets
  • touch_start() - Runs when object is touched
  • timer() - Runs at regular intervals
  • listen() - Runs when chat is heard
3. Functions

Functions are commands that perform actions. Every function call must end with a semicolon ;

  • llSay() - Makes object speak in chat
  • llSetColor() - Changes object color
  • llSetText() - Displays floating text

Your First Script: The Greeter

Let's create an object that says "Hello, World!" when touched.

1 Create a Prim

Right-click the ground, select Create, then click to rez a cube.

2 Enter Edit Mode

Right-click your cube and select Edit.

3 Open the Content Tab

In the Edit window, click the Content tab to view the object's inventory.

4 Create New Script

Click New Script. The script editor opens with default code.

5 Examine the Default Script

The default script looks like this:

default
{
    state_entry()
    {
        llSay(0, "Hello, Avatar!");
    }

    touch_start(integer total_number)
    {
        llSay(0, "Touched.");
    }
}

What's happening?

  • state_entry() runs once when the script starts
  • touch_start() runs every time someone touches the object
  • llSay(0, "text") makes the object speak on channel 0 (public chat)
6 Create Your Custom Script

Delete everything and replace with this simpler version:

// My First Interactive Object
// This script makes the object greet when touched

default
{
    touch_start(integer total_number)
    {
        llSay(0, "Hello, World! You touched me.");
    }
}
About Comments: Lines starting with // are comments. The script ignores them—they're notes for you and other scripters!
7 Save and Compile

Click Save. If successful, the button grays out. If there are errors, they appear in chat below the code.

8 Test Your Script!

Close the editor and click your cube. Check local chat—you should see: [YourObjectName]: Hello, World! You touched me.

Congratulations! You've written your first working LSL script and created an interactive object!
Common Errors:
  • Missing semicolon: Every statement must end with ;
  • Mismatched braces: Every { needs a closing }
  • Wrong quotes: Use double quotes " for strings, not single quotes

Lesson 2: Variables, Colors, and Personalization

Understanding Variables

Variables are named containers that store information. Think of them as labeled boxes where you keep data for later use.

LSL Data Types

Type Description Example
integer Whole numbers 42, -10, 0
float Decimal numbers 3.14, -0.5, 1.0
string Text in quotes "Hello", "Sorin Todys"
vector 3 floats (position, color) <1.0, 0.0, 0.0> (red)
key Unique identifier (UUID) Avatar or object ID
list Collection of values [1, 2.5, "text"]

Working with Colors

Colors are represented as vectors with RGB (Red, Green, Blue) values from 0.0 to 1.0.

// Common Colors
vector RED     = <1.0, 0.0, 0.0>;
vector GREEN   = <0.0, 1.0, 0.0>;
vector BLUE    = <0.0, 0.0, 1.0>;
vector WHITE   = <1.0, 1.0, 1.0>;
vector BLACK   = <0.0, 0.0, 0.0>;
vector YELLOW  = <1.0, 1.0, 0.0>;
vector PURPLE  = <1.0, 0.0, 1.0>;
vector CYAN    = <0.0, 1.0, 1.0>;
vector ORANGE  = <1.0, 0.5, 0.0>;

Project 1: Color-Changing Block

Let's make an object that changes color when touched.

// Color-Changing Block Script
// Changes to red when touched

default
{
    touch_start(integer total_number)
    {
        // Announce the change
        llSay(0, "Ouch! You touched me, turning red!");
        
        // Define red color
        vector redColor = <1.0, 0.0, 0.0>;
        
        // Apply color to all sides
        llSetColor(redColor, ALL_SIDES);
    }
}
Understanding llSetColor():
  • First parameter: vector color
  • Second parameter: which face to color
  • ALL_SIDES is a constant that means "all faces"
  • You can specify individual faces: 0, 1, 2, etc.

Project 2: Rainbow Cycler

Let's make the object cycle through colors on each touch.

// Rainbow Color Cycler
// Cycles through colors on each touch

integer colorIndex = 0;  // Track current color
list colors = [
    <1.0, 0.0, 0.0>,  // Red
    <1.0, 0.5, 0.0>,  // Orange
    <1.0, 1.0, 0.0>,  // Yellow
    <0.0, 1.0, 0.0>,  // Green
    <0.0, 0.0, 1.0>,  // Blue
    <0.5, 0.0, 1.0>,  // Purple
    <1.0, 0.0, 1.0>   // Magenta
];

default
{
    state_entry()
    {
        llSay(0, "Touch me to cycle through rainbow colors!");
    }
    
    touch_start(integer total_number)
    {
        // Get the current color from the list
        vector currentColor = llList2Vector(colors, colorIndex);
        
        // Apply the color
        llSetColor(currentColor, ALL_SIDES);
        
        // Move to next color
        colorIndex++;
        
        // Loop back to start if we reach the end
        if (colorIndex >= llGetListLength(colors))
        {
            colorIndex = 0;
        }
        
        llSay(0, "Color " + (string)(colorIndex + 1) + " of " + 
              (string)llGetListLength(colors));
    }
}

Project 3: Personal Greeter

Make the object greet users by name!

// Personal Greeter Script
// Greets each toucher by name

default
{
    touch_start(integer total_number)
    {
        // Get the key of who touched
        key toucherID = llDetectedKey(0);
        
        // Get their username
        string toucherName = llKey2Name(toucherID);
        
        // Greet them personally
        llSay(0, "Hello, " + toucherName + "! Welcome!");
        
        // Change color to green for friendliness
        llSetColor(<0.0, 1.0, 0.0>, ALL_SIDES);
    }
}
Key Functions for Detection:
  • llDetectedKey(0) - Returns the UUID of the first toucher
  • llDetectedName(0) - Returns display name of toucher
  • llKey2Name(key) - Converts key to legacy name
  • The 0 parameter means "first toucher" (useful when multiple avatars touch simultaneously)

Advanced: Floating Text Display

// Interactive Info Display
// Shows status in floating text

integer touchCount = 0;

default
{
    state_entry()
    {
        llSetText("Touch me!\nCount: 0", <1,1,1>, 1.0);
    }
    
    touch_start(integer total_number)
    {
        touchCount++;
        
        string toucherName = llDetectedName(0);
        
        llSetText("Last touched by:\n" + toucherName + 
                  "\nTotal touches: " + (string)touchCount,
                  <0,1,1>, 1.0);
        
        llSay(0, "Touch #" + (string)touchCount + " by " + toucherName);
    }
}
About llSetText():
  • First parameter: text string (use \n for new lines)
  • Second parameter: color vector
  • Third parameter: alpha (transparency) from 0.0 to 1.0
  • Use empty string "" to remove text

Lesson 3: State Machines - Creating a Light Switch

Understanding States

States allow objects to behave differently based on their current condition. A light switch has two states: ON and OFF. Each state responds to touches differently.

Why Use States?
  • Organize complex behaviors logically
  • Make code easier to read and maintain
  • Reduce conditional logic (fewer if/else statements)
  • Create clear, predictable object behaviors

State Syntax

// Basic state structure
default  // First state must always be 'default'
{
    state_entry()
    {
        // Runs when entering this state
    }
    
    touch_start(integer num)
    {
        // Change to another state
        state on;
    }
}

state on  // Custom state
{
    state_entry()
    {
        // Runs when entering 'on' state
    }
    
    touch_start(integer num)
    {
        // Return to default state
        state default;
    }
}

Complete Light Switch Script

// Interactive Light Switch
// Touch to toggle between ON and OFF

// OFF State (default)
default
{
    state_entry()
    {
        // Set appearance for OFF state
        llSetColor(<0.3, 0.3, 0.3>, ALL_SIDES);  // Dark gray
        llSetText("LIGHT: OFF\nTouch to turn ON", <1,0,0>, 1.0);
        
        // Turn off any glow/fullbright
        llSetPrimitiveParams([
            PRIM_FULLBRIGHT, ALL_SIDES, FALSE,
            PRIM_GLOW, ALL_SIDES, 0.0
        ]);
        
        llSay(0, "Light is OFF");
    }
    
    touch_start(integer total_number)
    {
        llSay(0, "Turning light ON...");
        state on;  // Switch to ON state
    }
}

// ON State
state on
{
    state_entry()
    {
        // Set appearance for ON state
        llSetColor(<1.0, 1.0, 0.8>, ALL_SIDES);  // Warm white
        llSetText("LIGHT: ON\nTouch to turn OFF", <0,1,0>, 1.0);
        
        // Make it glow and bright
        llSetPrimitiveParams([
            PRIM_FULLBRIGHT, ALL_SIDES, TRUE,
            PRIM_GLOW, ALL_SIDES, 0.3
        ]);
        
        llSay(0, "Light is ON");
    }
    
    touch_start(integer total_number)
    {
        llSay(0, "Turning light OFF...");
        state default;  // Switch back to OFF state
    }
}
State Best Practices:
  • Use descriptive state names (on, off, open, closed)
  • Always set up appearance in state_entry()
  • The default state must always exist
  • Use states for truly different behaviors, not just simple toggles

Advanced: Three-State Light with Dimmer

// Three-State Dimmable Light
// OFF → DIM → BRIGHT → OFF

default  // OFF
{
    state_entry()
    {
        llSetColor(<0.2, 0.2, 0.2>, ALL_SIDES);
        llSetText("OFF\n(Touch for Dim)", <0.5,0.5,0.5>, 1.0);
        llSetPrimitiveParams([
            PRIM_FULLBRIGHT, ALL_SIDES, FALSE,
            PRIM_GLOW, ALL_SIDES, 0.0
        ]);
    }
    
    touch_start(integer num)
    {
        state dim;
    }
}

state dim  // DIM
{
    state_entry()
    {
        llSetColor(<1.0, 0.9, 0.7>, ALL_SIDES);
        llSetText("DIM\n(Touch for Bright)", <1,1,0>, 1.0);
        llSetPrimitiveParams([
            PRIM_FULLBRIGHT, ALL_SIDES, TRUE,
            PRIM_GLOW, ALL_SIDES, 0.1
        ]);
    }
    
    touch_start(integer num)
    {
        state bright;
    }
}

state bright  // BRIGHT
{
    state_entry()
    {
        llSetColor(<1.0, 1.0, 1.0>, ALL_SIDES);
        llSetText("BRIGHT\n(Touch for Off)", <0,1,0>, 1.0);
        llSetPrimitiveParams([
            PRIM_FULLBRIGHT, ALL_SIDES, TRUE,
            PRIM_GLOW, ALL_SIDES, 0.4
        ]);
    }
    
    touch_start(integer num)
    {
        state default;
    }
}

Alternative: Variable-Based Toggle

For simple ON/OFF behavior, you can also use a variable instead of states:

// Simple Toggle Light (Using Variable)
// Simpler than states for basic toggles

integer isOn = FALSE;  // Track state with variable

updateLight()
{
    if (isOn)
    {
        // ON appearance
        llSetColor(<1.0, 1.0, 0.8>, ALL_SIDES);
        llSetText("ON", <0,1,0>, 1.0);
        llSetPrimitiveParams([
            PRIM_FULLBRIGHT, ALL_SIDES, TRUE,
            PRIM_GLOW, ALL_SIDES, 0.3
        ]);
    }
    else
    {
        // OFF appearance
        llSetColor(<0.3, 0.3, 0.3>, ALL_SIDES);
        llSetText("OFF", <1,0,0>, 1.0);
        llSetPrimitiveParams([
            PRIM_FULLBRIGHT, ALL_SIDES, FALSE,
            PRIM_GLOW, ALL_SIDES, 0.0
        ]);
    }
}

default
{
    state_entry()
    {
        updateLight();
    }
    
    touch_start(integer num)
    {
        isOn = !isOn;  // Toggle (! means NOT)
        updateLight();
        llSay(0, "Light " + (string)(isOn ? "ON" : "OFF"));
    }
}
States vs Variables:
  • Use States when behaviors are very different in each mode
  • Use Variables for simple toggles or when the same events exist in all modes
  • States are better for complex, multi-mode objects
  • Variables are simpler for basic on/off functionality

Hands-On Exercises

Exercise 1: Color Mixer

Task: Create an object that cycles through primary colors (red, green, blue) on each touch and announces the current color.

Requirements:

  • Use a list to store colors
  • Track current color index
  • Display color name in chat
  • Loop back to first color after last

Exercise 2: Visitor Counter

Task: Create an object that counts how many times it's been touched and displays the count in floating text.

Requirements:

  • Track touch count in a variable
  • Display count in llSetText()
  • Show last toucher's name
  • Update display on each touch

Exercise 3: Traffic Light

Task: Create a three-state traffic light (red → yellow → green → red).

Requirements:

  • Three states: red, yellow, green
  • Each state has appropriate color
  • Floating text shows current signal
  • Touch advances to next signal

Exercise 4: Personalized Greeter

Task: Create an object that remembers and greets the object owner specially.

Requirements:

  • Detect if toucher is the owner
  • Give different greetings to owner vs others
  • Use llGetOwner() function
  • Display different colors for owner/visitor
Hint

Use: if (llDetectedKey(0) == llGetOwner())

Exercise 5: Door with States

Task: Create a simple door that opens and closes with different appearances.

Requirements:

  • Two states: closed and open
  • Closed: brown color, shows "CLOSED" text
  • Open: transparent, shows "OPEN" text
  • Use llSetAlpha() to make transparent
Hint

Use: llSetAlpha(0.3, ALL_SIDES) for transparency

Challenge: Interactive Info Kiosk

Task: Create an information kiosk that provides different info on each touch.

Requirements:

  • Store 5 different info messages in a list
  • Display different message on each touch
  • Change color for each message
  • Show message number in floating text
  • Include welcome message in state_entry()

Quick Reference Guide

Essential Functions

Function Purpose Example
llSay() Speak in chat llSay(0, "Hello!");
llSetColor() Change color llSetColor(<1,0,0>, ALL_SIDES);
llSetText() Floating text llSetText("Info", <1,1,1>, 1.0);
llDetectedKey() Get toucher UUID key id = llDetectedKey(0);
llDetectedName() Get toucher name string name = llDetectedName(0);
llGetOwner() Get owner UUID key owner = llGetOwner();

Common Events

  • state_entry() - Runs when entering a state
  • touch_start(integer num) - Runs when touched
  • touch_end(integer num) - Runs when touch released

Debugging Tips

  • Always check for missing semicolons
  • Make sure braces {} are balanced
  • Use llOwnerSay() for debugging (only you see it)
  • Add comments to complex code
  • Test one feature at a time
  • Read error messages carefully—they often tell you the line number

Course Complete!

Congratulations on completing Introduction to Scripting!

You've learned the fundamentals of LSL and can now create interactive objects that respond to touches, change appearance, and maintain different states.

What You've Mastered

  • LSL script structure and syntax
  • Event-driven programming concepts
  • Variables and data types
  • Color manipulation and visual effects
  • User detection and personalization
  • State machines for complex behaviors

Next Steps

  • Complete all hands-on exercises
  • Experiment with combining concepts
  • Take SCR-401: Advanced Scripting
  • Explore the LSL Wiki for more functions
require('/var/www/alifevirtual/header.php'); ?>
SCR-301 Intermediate The School of Creation
Lead Instructor

Sorin Todys - Advanced expert with 20+ years of experience in virtual worlds


All classes take place in Alife Virtual at our dedicated Alife Virtual School region

Introduction to Scripting - Your First Interactive Object (SCR-301)

Introduction to Scripting - Your First Interactive Object - Alife Virtual School

Learn and Grow at Alife Virtual School

Part of The School of Creation | Difficulty: Intermediate


Course Details
  • Course Code: SCR-301
  • School: The School of Creation
  • Difficulty Level: Intermediate
  • Course Description: Write your first Linden Scripting Language (LSL) script to make objects respond to touch and create truly interactive experiences in Alife Virtual.
  • Lead Instructor: Sorin Todys, Advanced LSL Expert

1. COURSE OVERVIEW

Welcome to the World of Interaction!

Welcome, creators! If you've ever looked at a static object in Alife Virtual and wished it could *do* something, then you've come to the right place. This course is your gateway into the fascinating world of the Linden Scripting Language (LSL). Scripting is the "brain" that gives objects behavior, turning a simple block of wood into a door that opens, a button that gives gifts, or a light that illuminates a room.

In SCR-301, we will demystify scripting and empower you to bring your own creations to life. We'll start from the very beginning, understanding the core concepts of LSL, and by the end, you'll have scripted your very first interactive object that responds to you and other avatars. This is a hands-on, practical course designed to give you a solid and confident start.

Learning Objectives

Upon successful completion of this course, you will be able to:

  • Understand the fundamental structure of an LSL script, including states, events, and functions.
  • Confidently use the in-world script editor in the Firestorm Viewer to create, edit, and save scripts.
  • Write a script that makes an object communicate in local chat using the llSay() function.
  • Implement the touch_start event to make objects respond to clicks.
  • Control an object's color dynamically using the llSetColor() function and vector data types.
  • Personalize interactions by detecting the name of the avatar touching your object.
  • Create a simple "state machine" to give an object different behaviors, such as an on/off switch.

What You Will Master

By the end of this course, you will have moved beyond being a static builder and will have become an interactive creator. You will master the ability to take any basic prim you create and imbue it with life. You'll be able to confidently build objects that greet visitors, change appearance on command, and function as simple devices. This foundational knowledge is the most crucial step in your journey to becoming an advanced LSL scripter.

Prerequisites

Required: Basic building skills in Alife Virtual. You must be comfortable with creating a prim (a cube, sphere, etc.), moving it, and accessing its edit menu. We recommend our BLD-101: Building Fundamentals course if you are new to creating objects.

Lead Instructor

This course is taught by Sorin Todys, our resident expert in the Linden Scripting Language. With over 20 years of experience scripting in virtual worlds, Sorin has a unique talent for making complex programming concepts easy to understand for beginners and intermediate learners alike. He is passionate about empowering students to unlock their full creative potential through code.

2. LESSON 1: The Magic of "Hello, World!" - Your First Script

Theory: What is a Script?

Think of a script as a recipe or a set of instructions that you place inside an object. The object will follow these instructions precisely. LSL is an event-driven language. This means a script spends most of its time waiting for something to happen (an "event"). Events can be anything: an avatar touching the object, a timer going off, or a message being received from another script.

When an event occurs, the script looks for a matching set of instructions (an "event handler") and executes the code inside it. The fundamental structure you'll always see is:

  • States: A script is always in a "state." The starting state is always called default. States help organize your script's behavior, like having a "door open" state and a "door closed" state.
  • Events: These are the triggers. The most common one we'll start with is touch_start, which fires when someone clicks on the object.
  • Functions: These are the actions. They are commands that tell the object to *do* something, like speak (llSay()), change color (llSetColor()), or move (llSetPos()). Every function call must end with a semicolon ;.

Step-by-Step: Creating a "Greeter" Object

Let's make an object say "Hello, World!" when you touch it. This is the traditional first step in learning any new programming language.

  1. Rez a Prim: Right-click the ground and choose Create. A build menu will appear. Click on the ground again to "rez" (create) a simple wooden cube. This cube is our object, or "prim."
  2. Enter Edit Mode: Right-click your new cube and select Edit from the pie menu. You'll see arrows and tools appear around your object.
  3. Navigate to the Content Tab: In the Edit window that pops up, find and click on the Content tab. This is the inventory of the object.
  4. Create a New Script: Click the New Script button. A new item named "New Script" will appear in the Content tab, and the script editor window will open, pre-filled with a default script.
  5. Examine the Default Script: The default script looks something like this. Let's break it down.
    default { state_entry() { llSay(0, "Hello, Avatar!"); } touch_start(integer total_number) { llSay(0, "Touched."); } }
    • default { ... }: This is our main state. All the code lives inside these curly braces.
    • state_entry() { ... }: This event runs once when the script first starts or is reset. Here, it makes the object say "Hello, Avatar!".
    • touch_start(...) { ... }: This event runs every time someone touches the object. Here, it makes the object say "Touched.".
  6. Modify the Script: Let's make it our own. Delete the entire contents of the script window and replace it with this simpler version. This version will only react to a touch.
    default { touch_start(integer total_number) { llSay(0, "Hello, World! You touched me."); } }
  7. Save Your Script: Click the Save button at the bottom of the script editor. The script will compile. If there are no errors, the button will become grayed out. If there are errors, they will appear in the chat window below the code. The most common error is a missing semicolon ;!
  8. Test It!: Close the script editor and the Edit window (by pressing Escape or closing the window). Now, left-click on your cube. Look at the local chat in the bottom left of your screen. You should see your object saying: [Object] YourObjectName: Hello, World! You touched me.

Key Concepts Highlighted

  • Prim: The basic building block in Alife Virtual (e.g., a cube, sphere).
  • Script Editor: The in-world tool for writing and saving LSL code.
  • default state: The primary container for your script's logic.
  • touch_start() event: The trigger that executes code when an object is clicked.
  • llSay() function: The command to make an object speak in local chat.
  • Semicolon ;: The most important piece of punctuation in LSL. Every complete command statement must end with one. Forgetting it is the #1 cause of syntax errors.

Congratulations! You've just written your first working script and created an interactive object. You've taken your first step into a larger world of creation!

3. LESSON 2: Beyond Words - Changing Colors and Detecting Who Touched You

Theory: Variables and More Functions

In Lesson 1, our object did the same thing every time. To make it more dynamic, we need to introduce variables and new functions. A variable is like a labeled box where you can store information for the script to use later. This information can be a number, a piece of text, or even a color.

  • Data Types: Every variable has a type. The most common are:
    • integer: A whole number (e.g., 5, -10, 1000).
    • float: A number with a decimal point (e.g., 3.14, -0.5).
    • string: A piece of text, enclosed in double quotes (e.g., "Hello, Sorin!").
    • vector: A set of three floats, used for positions, forces, and most importantly for us, colors (e.g., <1.0, 0.0, 0.0> for red).
    • key: A unique identifier for any person, object, or item in the world.
  • New Functions:
    • llSetColor(vector color, integer face): This function changes the color of the object. It requires a vector for the color and an integer specifying which face of the prim to color. We can use the special constant ALL_SIDES to color the entire object.
    • llDetectedKey(integer index): When used inside a touch event, this function returns the unique key of the avatar who touched the object.
    • llGetUsernameFromKey(key id): This function takes a user's key and returns their username as a string.

Practical Example 1: The Color-Changing Block

Let's modify our script to make the block turn bright red when touched.

  1. Open the script from Lesson 1 by editing the cube, going to the Content tab, and double-clicking your script.
  2. Modify the code inside the touch_start event. We'll add the llSetColor function.
    default { touch_start(integer total_number) { // Make the object say something in chat llSay(0, "Ouch! You touched me, so I'm turning red."); // Define the color red as a vector vector red_color = <1.0, 0.0, 0.0>; // Apply the color to all sides of the prim llSetColor(red_color, ALL_SIDES); } }

    Note on Colors: Color vectors use RGB (Red, Green, Blue) values from 0.0 (none of that color) to 1.0 (full intensity). So <1.0, 0.0, 0.0> is pure red, <0.0, 1.0, 0.0> is pure green, and <1.0, 1.0, 1.0> is white.

    Note on Comments: The line starting with // is a comment. The script ignores it. It's for you to leave notes for yourself or others reading your code!

  3. Click Save and close the editor. Touch your cube. It should now turn bright red and speak to you!

Practical Example 2: The Personal Greeter

Now, let's make the greeting personal. Instead of "Hello, World!", it will say hello to the specific person who touched it.

  1. Edit your script again. This time, we'll use variables to store the toucher's information.
  2. Replace your code with the following:
    default { touch_start(integer total_number) { // 1. Get the unique key of the person who touched the object. key toucher_id = llDetectedKey(0); // 2. Convert that key into a username string. string toucher_name = llGetUsernameFromKey(toucher_id); // 3. Use the name in our llSay function. // The '+' symbol is used to join strings together. llSay(0, "Aha! It was " + toucher_name + " who touched me!"); } }
  3. Save the script. Now when you touch it, it will say your actual username! Try having a friend touch it and see what happens. This is the beginning of creating truly social and responsive objects.

4. LESSON 3: Smarter Objects - Using States to Create a Light Switch

Advanced Application: State Machines

Right now, our object does one thing when touched. What if we want it to do one thing on the first touch, and something different on the second touch? This is where states become incredibly powerful. We can create a script that acts like a light switch: the first touch turns it on, the second turns it off.

To do this, we will create two states: an "off" state and an "on" state. We will use the default state as our "off" state, and we will create a new, custom state called on.

Real-World Scenario: Scripting a Clickable Light

This is a classic and highly useful script. It demonstrates states, changing visual properties, and even adding light to the scene.

Best Practices for This Script:

  • Clear State Names: Naming your states logically (e.g., on, off, open, closed) makes your code much easier to read.
  • Use state_entry: The state_entry event is perfect for setting up the initial appearance and properties of an object as soon as it enters a new state.
  • Comment Your Logic: Explain *why* you are changing states. In a few months, you'll thank yourself for it.

Step-by-Step: The Light Switch Script

  1. Create a new cube prim (or use a