Spawn Vehicle Script - KimonoBoy/SHVDNTutorial-NucleiLite GitHub Wiki

We've covered a lot of Player related scripts, they're all fine, but not that interresting - I bet some of you just want to Spawn and try out different Vehicles - so it's time.

Let's create a Spawner script that spawns Vehicles

The Code

  1. Create a new file called VehicleSpawner.cs

  2. Copy and Paste the following code

using System;
using System.Windows.Forms;
using GTA;
using GTA.UI;
using GTA.Native;
using GTA.Math;

public class VehicleSpawner : Script
{
    public VehicleSpawner()
    {
        KeyDown += OnKeyDown;
    }

    public void OnKeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.D1 && e.Control)
        {
            SpawnVehicle(VehicleHash.Adder);
        } else if (e.KeyCode == Keys.D2 && e.Control)
        {
            SpawnVehicle(VehicleHash.Annihilator);
        } else if (e.KeyCode == Keys.D3 && e.Control)
        {
            SpawnVehicle(VehicleHash.Formula);
        }
    }

    public void SpawnVehicle(VehicleHash vehicleHash)
    {
        Model vehicleModel = new Model(vehicleHash);
        vehicleModel.Request();

        Vector3 spawnPosition = Game.Player.Character.Position + Game.Player.Character.ForwardVector * 3.0f;
        float vehicleHeading = Game.Player.Character.Heading + 90.0f;

        GTA.Vehicle vehicle = World.CreateVehicle(vehicleModel, spawnPosition, vehicleHeading);

        vehicleModel.MarkAsNoLongerNeeded();
    }
}
  1. Reload() and press one of the following key combinations

CTRL + 1: Spawns Adder
CTRL + 2: Spawns Annihilator
CTRL + 3: Spawns Formula

image

In the Mod Menu-section we'll be creating loops that allows us to select and spawn any vehicle directly from our menu.

Code Breakdown - Simplified

A lot of new things are going on here - this is the hardest script we've made this far. Not to worry, I got you covered!

using GTA.Native;
using GTA.Math;

These two new using-statements are required to work with GTA-positions (and other math related features) and GTA-Hashes


    public void SpawnVehicle(VehicleHash vehicleHash)
    {
        Model vehicleModel = new Model(vehicleHash);
        vehicleModel.Request();

        Vector3 spawnPosition = Game.Player.Character.Position + Game.Player.Character.ForwardVector * 3.0f;
        float vehicleHeading = Game.Player.Character.Heading + 90.0f;

        GTA.Vehicle vehicle = World.CreateVehicle(vehicleModel, spawnPosition, vehicleHeading);

        vehicleModel.MarkAsNoLongerNeeded();
    }
public void SpawnVehicle(VehicleHash vehicleHash)

We've created a new method that accepts one argument (input), the input is of Data Type VehicleHash - the VehicleHash determines which Vehicle to be spawned - you can see a full list of all available VehicleHashes at VehicleHashes


        Model vehicleModel = new Model(vehicleHash);
        vehicleModel.Request();

The Model class is part of the ScriptHookVDotNet library and it's used to create new models of game-assets - the vehicleModel.Request() requests the asset


Vector3 spawnPosition = Game.Player.Character.Position + Game.Player.Character.ForwardVector * 3.0f;

A Vector3 is a position in game made of x-coordinates, y-coordinates and z-coordinates so we want our variable to hold our characters current position + an additional ForwardVector so that the Vehicle is not spawned directly on our character


float vehicleHeading = Game.Player.Character.Heading + 90.0f;

A heading is the rotation - so we get our Character's current heading plus an additional 90 degrees - this makes the Driver Seat be right infront of the Character


GTA.Vehicle vehicle = World.CreateVehicle(vehicleModel, spawnPosition, vehicleHeading);

Finally, we create the actual vehicle with the above variables World.CreateVehicle() takes three arguments (inputs) - the model to spawn, where to spawn it and its rotation


vehicleModel.MarkAsNoLongerNeeded();

Once the vehicle is spawned, we don't need the model in memory anymore, so we remove it with the MarkAsNoLongerNeeded() method. This is always a good practice to perform on any models you create - for the three vehicle we've spawned it doesn't really matter, but if we're to create many more models, the Game Engine can quickly be overwhelmed if we don't remove the resources from memory when they are no longer needed.

You're probably wondering how you're supposed to know all the different features of ScriptHookVDotNet, but don't worry, we'll cover how to find the available documentation later!

Code Breakdown - Advanced

Let's make a better understanding of what's actually going on here

using System;
using System.Windows.Forms;
using GTA;
using GTA.UI;
using GTA.Native;
using GTA.Math;

Remember earlier when we talked about the use of the using-directives and namespaces. This time around we use it to implement som new libraries, in our VehicleSpawner script, from the ScriptHookVDotNet framework (GTA.Native and GTA.Math)

You can see a full list of all valid namespaces, objects and their functionality at ScriptHookVDotNet Documentation

    public void SpawnVehicle(VehicleHash vehicleHash)
    {
        Model vehicleModel = new Model(vehicleHash);
        vehicleModel.Request();

        Vector3 spawnPosition = Game.Player.Character.Position + Game.Player.Character.ForwardVector * 3.0f;
        float vehicleHeading = Game.Player.Character.Heading + 90.0f;

        GTA.Vehicle vehicle = World.CreateVehicle(vehicleModel, spawnPosition, vehicleHeading);

        vehicleModel.MarkAsNoLongerNeeded();
    }

Let's have a look at the first line here

public void SpawnVehicle(VehicleHash vehicleHash)

Declares a public method named SpawnVehicle, which takes a single parameter/argument of type VehicleHash and returns void (nothing).

VehicleHash is an enum type that represents the various types of vehicles that can be spawned in the game. This enum type is defined in the ScriptHookVDotNet library and contains values for all of the vehicles in the game, such as cars, motorcycles, planes, boats, etc.

You can learn more about enums at Enums

By specifying the VehicleHash parameter in the method signature, the caller of this method must pass in a valid VehicleHash value to spawn the desired type of vehicle. For example, if the caller wants to spawn a car, they can pass in the VehicleHash.Comet value, which represents the Comet car in the game.

Overall, this method abstracts away the details of creating a new Vehicle and setting its properties, such as its position and heading.


Model vehicleModel = new Model(vehicleHash);

Creates a new instance of the Model class and assigns it to the vehicleModel variable. The Model class is a type in the ScriptHookVDotNet library that represents a 3D model of an object in the game, such as a vehicle or a weapon.

When a new Model is created, it is initialized with the 3D model data for the specified vehicle type, which is loaded from the game files. This allows the game engine to create and manipulate a 3D representation of the vehicle in memory.

To summarize: This sets up the vehicleModel to be used to create a new Vehicle later in the method. It ensures that the 3D model data for the vehicle type is loaded into memory, so that it can be used to render the vehicle when it is spawned in the game world.


vehicleModel.Request();

Requests that the game engine load the 3D model data for the vehicleModel into memory. This is necessary because the game does not load all of the 3D models for objects in the game world into memory at once, in order to conserve system resources.

When a Model is created, it does not automatically load the 3D model data into memory. Instead, the Request method is called on the Model to trigger the loading of the data. When the Request method is called, the game engine will begin loading the 3D model data for the object in the background, asynchronously.

Once the 3D model data has been loaded into memory, the vehicleModel will be ready to be used to create a new Vehicle.

Note: It's important to note that the Request method does not block the execution of the game code. Instead, it allows the game to continue running while the 3D model data is loaded in the background. Once the data has been loaded, the game engine will signal that it is ready to be used by the code, which can then proceed to create the Vehicle.


Vector3 spawnPosition = Game.Player.Character.Position + Game.Player.Character.ForwardVector * 3.0f;

Calculates the position where the new Vehicle will be spawned in the game world.

The Game class is part of the ScriptHookVDotNet library and provides access to various game-related properties and methods. Here it's used to get the current position and facing direction of the player's character.

The Game.Player.Character.Position property returns a Vector3 that represents the current position of the player's character in the game world.

The Game.Player.Character.ForwardVector property returns a Vector3 that represents the direction that the player's character is facing. Multiplying this vector by 3.0f creates a new vector that is three units in front of the player's character.

By adding these two vectors together using the + operator, the code calculates the position where the new Vehicle will be spawned. The resulting Vector3 is assigned to the spawnPosition variable, which will be used when creating the new Vehicle.

Overall, this code calculates the position where the new vehicle will spawn, based on the current position and facing direction of the player's character.


float vehicleHeading = Game.Player.Character.Heading + 90.0f;

Calculates the *heading (or orientation) of the new Vehicle when it is spawned in the game world.

The Game.Player.Character.Heading property returns a float value that represents the current heading of the player's character in the game world. This value represents the direction that the character is facing, in degrees, with 0 degrees pointing north, 90 degrees pointing east, 180 degrees pointing south, and 270 degrees pointing west.

By adding 90 degrees to the player's character's heading, the code calculates the orientation of the new Vehicle. Adding 90 degrees causes the vehicle to be oriented perpendicular to the direction that the player's character is facing, placing the driver-seat right infront of the character.

The resulting float value is assigned to the vehicleHeading variable, which will be used when creating the new Vehicle.

Overall, this calculates the orientation of the new vehicle when it is spawned, based on the current heading of the player's character.


GTA.Vehicle vehicle = World.CreateVehicle(vehicleModel, spawnPosition, vehicleHeading);

Creates a new Vehicle and assigns it to the vehicle variable.

The Vehicle class is part of the ScriptHookVDotNet library and represents a vehicle in the game world, such as a car, motorcycle, or plane.

The World class is also part of the ScriptHookVDotNet library and provides access to various methods related to creating and managing game objects in the world. In this line of code, it is used to create a new Vehicle.

The CreateVehicle() method of the World class takes three arguments: the vehicleModel that was created earlier, the spawnPosition vector that represents the position where the vehicle will be spawned, and the vehicleHeading float value that represents the orientation of the vehicle when it is spawned.

When this method is called, the game engine creates a new Vehicle based on the specified Model, position, and heading, and adds it to the game world. The resulting Vehicle is assigned to the vehicle variable, which can be used to access and manipulate the vehicle in the game world.

Overall this code creates a new Vehicle and adds it to the game world, based on the Model, position, and heading that were specified earlier in the method.


vehicleModel.MarkAsNoLongerNeeded();

Marks the vehicleModel as no longer needed, allowing the game engine to unload its associated 3D model data from memory and free up system resources.

When a Model is created, it loads the 3D model data for the associated game into memory. This data can take up a significant amount of system resources, especially if many different types of game objects are being used.

By calling the MarkAsNoLongerNeeded() method on the vehicleModel, the game engine is notified that the 3D model data for the vehicle is no longer needed and can be unloaded from memory. This frees up system resources that can be used by other parts of the game.

It's important to note that the MarkAsNoLongerNeeded() method does not delete the Model itself, only the associated 3D model data. The Model can still be used to create new instances of the associated game, as long as its Request() method is called again to reload the 3D model data into memory.

To summarize: This code allows the script to efficiently manage system resources by unloading 3D model data that is no longer needed, while still retaining the flexibility to create new instances of game objects as needed.

Conclusion

We've created a VehicleSpawner script that can spawn any Vehicle in game, simply by passing in a VehicleHash to the method creating the vehicle

Previous - Super Jump Script
Next - Give All Weapons Script