Saturday, December 29, 2007

NWN Scripting - Naming an Object Part 1

Today, I decided to work on a script for NWN1 that will take a players character first name and apply it to an item. Nothing really hard but I might as well document my pain at trying to work out how to do it. As others have noted elsewhere, I struggle to spell words correctly, or indeed keep my writing coherent. So as you can see, scripting can be a real pain in the backside for me.

My first pass at this script is to first get the players name using GetName(oPC) with oPC being the PC. This returns the Firtsname and the Surname of the PC, with a space separating them. I now need to take the leftmost string, as this is what I want to use to name an item.
Easier said than done it seems, when I scan the Name of the PC for the location of a space it returns a 0. Seeing that the name of the PC is 13 characters long and the space is in the middle, well this sucks.

Well spent most of the day on this, back and forth and realised I am truly a sucky coder but I got it to work at least. I can now pull the first name of characters that have a spaces in them.

Only problem now is that names with no spaces have the front character truncated. I am too tired to really stress so I put it up on Bioware, in hope of some answers.

Read it here on Bioware...
http://nwn.bioware.com/forums/viewtopic.html?topic=609475&forum=47&sp=0#5554701

Amazing, the community resonded and suddenly my code has gone from a monster to something that is rather useful.

Below is what a gifted script writer can do. Axe Murderer, took my rather horrific piece of code and made something that is rather elegant. Now I just need to work my way through it to understand it better.

//Put this on action taken in the conversation editor

string GetFirstName( object oCreature) // Function to get the First Name

{ if( !GetIsObjectValid( oCreature)) return ""; // Check to see if it is a PC

string sName = GetName( oCreature);
int iPos = FindSubString( sName, " ");// Find the space in the Full name
if( iPos < 0) return sName; // If there are no spaces the name is made default

// If there are spaces then do this
while( iPos == 0)
{ sName = GetStringRight( sName, GetStringLength( sName) -1);
iPos = FindSubString( sName, " ");
}
// Ternary condition which does an if else sorto of.
return ((iPos < 0) ? sName : GetStringLeft( sName, iPos));
}


void main()
{ object oPC = GetPCSpeaker(); // PC who is speaking to NPC
string sFirstName = GetFirstName( oPC); // Get the PC's first name.
SendMessageToPC( oPC, "DEBUG ks_namer: sFirstName is " + sFirstName );
SpeakString( "My First name is " +sFirstName +" and I am " +IntToString( GetStringLength( sFirstName)) +" characters long");//Spor Debug
}