Search Unity

Splitting Strings

Discussion in 'Scripting' started by Noah-Cristino, Jun 11, 2015.

  1. Noah-Cristino

    Noah-Cristino

    Joined:
    May 25, 2015
    Posts:
    24
    I am writing a script to equip weapons when you collide with the pickup version of them. I named all of the pickups: "Pickup Weaponname". Here is the collision part:
    Code (CSharp):
    1.  
    2. private void OnCollisionEnter(Collision collision)
    3.     {
    4.         if ( collision.gameObject.name == "zombie" )
    5.         {
    6.             Destroy(collision.gameObject);
    7.         }
    8.     }
    9.  
    I want it to split the name of what it collided with (the Collision collision part) into the first 6 characters and the rest of the characters (not counting space). Then if the first 6 chars are Pickup it prints the end part with in the example would be "Weaponname". Please help!
     
  2. Iron-Warrior

    Iron-Warrior

    Joined:
    Nov 3, 2009
    Posts:
    838
    Code (csharp):
    1. string pickup = "Pickup EnergySword";
    2. string weaponName = pickup.Substring(7);
    3. Debug.Log(weaponName);
    There's quite a few ways to do this, and many that are much more robust, such as String.Split() with the delimiter being the whitespace. You can read about other string methods here.
     
    Noah-Cristino likes this.
  3. Noah-Cristino

    Noah-Cristino

    Joined:
    May 25, 2015
    Posts:
    24
  4. Noah-Cristino

    Noah-Cristino

    Joined:
    May 25, 2015
    Posts:
    24
    @Iron-Warrior Substring does not work it errors this: Assets/Collision.cs(17,46): error CS1061: Type `Collision' does not contain a definition for `Substring' and no extension method `Substring' of type `Collision' could be found (are you missing a using directive or an assembly reference?)
     
  5. Noah-Cristino

    Noah-Cristino

    Joined:
    May 25, 2015
    Posts:
    24
    Also Substring is red
     
  6. Iron-Warrior

    Iron-Warrior

    Joined:
    Nov 3, 2009
    Posts:
    838
    You would need to call the method on the gameObject.name, not the collision itself.
     
    Noah-Cristino likes this.
  7. Noah-Cristino

    Noah-Cristino

    Joined:
    May 25, 2015
    Posts:
    24