Skip to content
View in the app

A better way to browse. Learn more.

LCPDFR.com

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

[C#] Vehicle Spawning Problems

Featured Replies

Sorry if I'm making a really stupid mistake here, I'm new to C# (and coding in general) but whenever I use code that creates a new vehicle, my plugin crashes as soon as it creates that vehicle. Strangely, if I reload the plugin like ~10 times it will stop crashing.  Spawning the ped works just fine, it's just the vehicle that's causing the problem. This has been driving me insane for a while and I'm not sure what the issue is.

 

I'm also not entirely sure what the GameFiber stuff does, is there any documentation that explains this in-depth?

 

Any help or advice is massively appreciated, the code and RPH log is in the spoiler.

 

Spoiler

        public static void Main()
        {
            GameFiber.StartNew(delegate()
            {
                Game.DisplayNotification("Space's Plugin has loaded");

                while (true)
                {
                    while (true)
                    {
                        GameFiber.Yield();
                        if (Game.IsKeyDown(Keys.F8))
                            break;
                    }

                    Game.DisplayNotification("~b~Spawning ped and vehicle");
                    Game.LogTrivial("Spawning ped and vehicle");

                    Vehicle vehicle = new Vehicle("FBI2", Game.LocalPlayer.Character.Position);
                    Game.LocalPlayer.Character.WarpIntoVehicle(vehicle, -1);

                    Ped normPed = new Ped(Game.LocalPlayer.Character.GetOffsetPositionFront(5f));
                }
                
                // I'm aware that this is unreachable with the code in its current state
                GameFiber.Hibernate();
            });
        }

[3/25/2020 2:46:11 PM.521] Space's Plugin: Spawning ped and vehicle.
[3/25/2020 2:46:12 PM.015] Space's Plugin: 
[3/25/2020 2:46:12 PM.015] Space's Plugin: ==============================
[3/25/2020 2:46:12 PM.015] Space's Plugin: UNHANDLED EXCEPTION DURING GAME FIBER TICK
[3/25/2020 2:46:12 PM.016] Space's Plugin: ------------------------------
[3/25/2020 2:46:12 PM.016] Space's Plugin: Origin: Game fiber "<UNNAMED THREAD>".
[3/25/2020 2:46:12 PM.016] Space's Plugin: ------------------------------
[3/25/2020 2:46:12 PM.016] Space's Plugin: Exception type: System.InvalidOperationException
[3/25/2020 2:46:12 PM.016] Space's Plugin: Exception message: Could not spawn new vehicle.
[3/25/2020 2:46:12 PM.016] Space's Plugin: ------------------------------
[3/25/2020 2:46:12 PM.016] Space's Plugin: Inner exceptions:
[3/25/2020 2:46:12 PM.016] Space's Plugin: ------------------------------
[3/25/2020 2:46:12 PM.016] Space's Plugin: Stack trace:
[3/25/2020 2:46:12 PM.016] Space's Plugin: at Rage.Vehicle.HandleVehicleCreation(Model model, Vector3 position, Single heading)
[3/25/2020 2:46:12 PM.016] at Rage.Vehicle..ctor(Model model, Vector3 position)
[3/25/2020 2:46:12 PM.016] at SpacePlugin.EntryPoint.<>c.<Main>b__0_0() in C:\Users\Space\Desktop\GTA V Stuff\Space's Plugin\SpacePlugin\SpacePlugin.cs:line 33
[3/25/2020 2:46:12 PM.017] at Rage.GameFiber.Main()

 

 

Edited by Space.

You don't need a call to Hibernate() as this tells the thread to sleep until another thread wakes it up. The result means it stops processing (it won't even loop through) which means it will block any other threads from processing further if not done concurrently. (Feel free to look up information on multi-threading)

 

What you're doing in your while loop is correct, Yield the thread, this allows other threads to tick through as well and thus not block the game from executing.

However having two while loops inside each other not so much. Everything below the second loop won't execute at all.

 

I would add a safety check in so that you're not trying to warp the player into a car that doesn't yet exist.

 

I won't post any code yet on how to solve your problem. I'd much prefer to tell you how to fix it and see if you can learn yourself. However if you still struggle by all means come back to me and I'll help out further.

 

Good luck! 🙂

 

Live Streaming daily from 8pm GMT (UK) at https://twitch.tv/OfficialLukeD - I play a variety of things 😄

Join my official discord server for support, general chat and my stream schedule! https://discord.gg/Mddj7PQ

  • Author
2 hours ago, LukeD said:

 

 

Hey, thank you! I really appreciate your reply. I managed to replace the second while loop by using an If statement to see if F8 was pressed (not sure if this was the right way to go about it) and I managed to prevent the crashing by using vehicle.IsValid() and using a try-catch to catch the exception.. again, not entirely sure if this was the right way to go about it, but at least it works now so that's an improvement from last time. Do you have any advice on how else I could have done this? I couldn't think of a way to handle the exception from IsValid() other than to use a try-catch, though I feel like this is probably inefficient. (I also understand this is probably extremely painful to look at) 🙂

 

Spoiler

        public static void Main()
        {
            GameFiber.StartNew(delegate()
            {
                Game.DisplayNotification("Space's Plugin has loaded");

                while (true)
                {
                    GameFiber.Yield();
                    if (Game.IsKeyDown(Keys.F8))
                    {
                        Game.DisplayNotification("~b~Spawning ped and vehicle.");

                        try
                        {
                            Vehicle vehicle = new Vehicle("FBI2", Game.LocalPlayer.Character.GetOffsetPositionFront(5f));
                            if (vehicle.IsValid())
                                Game.LocalPlayer.Character.WarpIntoVehicle(vehicle, -1);

                            Ped normPed = new Ped(Game.LocalPlayer.Character.GetOffsetPositionFront(5f));
                            if (normPed.IsValid())
                            {
                                normPed.Inventory.GiveNewWeapon("weapon_pistol", -1, true);
                                normPed.Tasks.FightAgainst(Game.LocalPlayer.Character);
                            }
                        } catch (Exception e)
                        {
                            Game.LogTrivial(e.ToString());
                        }
                    }
                }
            });
        }

 

 

Edited by Space.

That's good work and much better code. A great improvement from your first try so well done 🙂

 

The try/catch is good for helping you find faults and deal with things internally. As you have done in your code you can see how you can stop the program from crashing and log the error. This is great for debugging or catching things you're not too sure about, and allows you to move on to better practices when releasing plugins.

 

The use of "IsValid()" is good, the alternative would be ".Exists()". Both achieve similar things. By testing for this condition before executing further code you eliminate the issue that the vehicle doesn't exist yet or hasn't spawned, if either of these things were true and you tried to warp your character into it you'd crash for trying to execute code against an object that doesn't exist in memory yet. In theory because of this check you don't need to try/catch the code anymore as you have checked for and made sure the vehicle exists before doing anything else with it. 

 

When in doubt, try/catch the problem to find the exact code that breaks. Once you know the problem, find out how to make it safe code. Once you have safety checked your code it shouldn't cause any issues (it's still code though and will still throw you a curveball every now and then). This is how you make good, well written code.

 

Keep going and you'll do well 🙂

Live Streaming daily from 8pm GMT (UK) at https://twitch.tv/OfficialLukeD - I play a variety of things 😄

Join my official discord server for support, general chat and my stream schedule! https://discord.gg/Mddj7PQ

  • Management Team

There is little reason to ever use IsValid as it does not perform a null check. Use Exists which is an extension method and hence can perform a null check. That way you will never get any exceptions you need to handle but instead just get false.

Please do not PM me unless really necessary (knowing you helps). If you think you need my attention in a topic, tag me.

  • Author

Thank you both massively for your replies, it will really help me going forward! One thing however,

 

9 hours ago, LMS said:

There is little reason to ever use IsValid as it does not perform a null check. Use Exists which is an extension method and hence can perform a null check. That way you will never get any exceptions you need to handle but instead just get false.

 

Whether I use Exists or IsValid, I get the same result, an exception if the vehicle doesn't exist. I believe this is so because the exception is coming from the act of creating a new vehicle, as opposed to actually doing stuff with it (this doesn't happen with peds, just vehicles). If I just create a new vehicle and do nothing with it, I'll still get the exception, the try-catch just prevents it from crashing the plugin. Is this normal/expected behaviour?

 

The exception message is "System.InvalidOperationException: Could not spawn new vehicle." (though it had already spawned the vehicle at this point)

 

Thanks. 🙂

Edited by Space.

3 hours ago, Space. said:

Thank you both massively for your replies, it will really help me going forward! One thing however,

 

 

Whether I use Exists or IsValid, I get the same result, an exception if the vehicle doesn't exist. I believe this is so because the exception is coming from the act of creating a new vehicle, as opposed to actually doing stuff with it (this doesn't happen with peds, just vehicles). If I just create a new vehicle and do nothing with it, I'll still get the exception, the try-catch just prevents it from crashing the plugin. Is this normal/expected behaviour?

 

The exception message is "System.InvalidOperationException: Could not spawn new vehicle." (though it had already spawned the vehicle at this point)

 

Thanks. 🙂

 

This will likely be down to what your plugin is actually doing.

 

Testing for "IsKeyDown" in a loop is fine but it will return true for every tick that it is considered "down". In other words, every time your while loop starts again it will test for if the key is down, this will happen faster than you can press a key on the keyboard. Therefore it will likely be triggering more than once and failing to spawn that type of car in the exact position because one already is being spawned there.

 

To test the theory create a simple bool outside of your loop such as "IsCarSpawned = false", and test the bool before you test the key is pressed. If the bool is false it will go on to test the kyebind.

If the key is down and you spawn the car at the end of the loop set the bool to true, so that the next time you tick round in the loop it will see the bool is true and wont evaluate if the key is pressed.

Live Streaming daily from 8pm GMT (UK) at https://twitch.tv/OfficialLukeD - I play a variety of things 😄

Join my official discord server for support, general chat and my stream schedule! https://discord.gg/Mddj7PQ

  • Author
4 hours ago, LukeD said:

To test the theory create a simple bool outside of your loop such as "IsCarSpawned = false", and test the bool before you test the key is pressed. If the bool is false it will go on to test the kyebind.

If the key is down and you spawn the car at the end of the loop set the bool to true, so that the next time you tick round in the loop it will see the bool is true and wont evaluate if the key is pressed.

 

This did fix the problem and so I was trying to think of some ways that I could delay checking if the key was being pressed again, I came up with the idea to use "GameFiber.Sleep(1000)" at the end of the If statement and it (much to my surprise) worked! And then I restarted my game and it stopped working, and it continues to not work every time I reload the plugin, unless.. while I'm in-game I copy and paste the same .dll into the plugins folder and then load it, it works? 🤔

 

Spoiler

        public static void Main()
        {
            GameFiber.StartNew(delegate()
            {
                Game.DisplayNotification("Space's Plugin has loaded.");

                while (true)
                {
                    GameFiber.Yield();
                    if (Game.IsKeyDown(Keys.F8))
                    {
                        Game.DisplayNotification("~b~Spawning ped and vehicle.");

                        if (Game.LocalPlayer.Character.IsInAnyVehicle(true))
                            Game.LocalPlayer.Character.CurrentVehicle.Delete();

                        Vehicle car = new Vehicle("FBI2", Game.LocalPlayer.Character.Position, Game.LocalPlayer.Character.Heading);
                        if (car.Exists())
                            Game.LocalPlayer.Character.WarpIntoVehicle(car, -1);

                        GameFiber.Sleep(1000);
                    }
                }
            });
        }

 

 

Edited by Space.

  • Management Team
13 hours ago, Space. said:

Whether I use Exists or IsValid, I get the same result, an exception if the vehicle doesn't exist. I believe this is so because the exception is coming from the act of creating a new vehicle, as opposed to actually doing stuff with it (this doesn't happen with peds, just vehicles). If I just create a new vehicle and do nothing with it, I'll still get the exception, the try-catch just prevents it from crashing the plugin. Is this normal/expected behaviour?

 

The exception message is "System.InvalidOperationException: Could not spawn new vehicle." (though it had already spawned the vehicle at this point)

 

That is indeed an issue with the vehicle creation itself then, not the IsValid/Exists check. It should not happen very often (I don't think I've had it once in my five years in V) but it apparently can occur for some people. Best to catch and handle accordingly. Basically the game could not create the vehicle and is telling you that.

Please do not PM me unless really necessary (knowing you helps). If you think you need my attention in a topic, tag me.

  • Author
13 hours ago, LMS said:

 

That is indeed an issue with the vehicle creation itself then, not the IsValid/Exists check. It should not happen very often (I don't think I've had it once in my five years in V) but it apparently can occur for some people. Best to catch and handle accordingly. Basically the game could not create the vehicle and is telling you that.

 

I see, very strange. Thanks, truly appreciated. 🙂

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

Recently Browsing 0

  • No registered users viewing this page.

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.