# Question
Title: Unity Random.Range when using Int, doesnt seem random at all?
I have a simple script that should cycle through 4 music tracks and select the next one to be played.

```
      nextSong = Random.Range(0, 3);

```

I've run my game approx 50 times and its never been 3. It's been 0 and 2 mostly but occasionally 1.

Is this something to do with it being rounded/casted from float to int?

nextSong is declared as an Int.

Anyone know whats going on here? Surely it cannot miss track 3 more than 50 times, or was it just many consecutive "lucky" rolls for 0 and 2?

Here is all the code in case it is relevant:

```
void Update () {
    if (!audioSource.isPlaying)
    {
        nextSong = Random.Range(0, 3);
        audioSource.clip = songs[nextSong];
        audioSource.Play();
        Debug.Log("should be playing next random track  number : " + nextSong + "called: " + songs[nextSong]);
    }
}

```

# Answer
> 5 votes
The documentation says that you will never get 3, the max is exclusive.

> public static int Range(int min, int max);
>
> Description
>
> Returns a random integer number between min \[inclusive\] and max \[exclusive\] (Read Only).
>
> Note that max is exclusive, so using Random.Range( 0, 10 ) will return values between 0 and 9. If max equals min, min will be returned.

So in your situation, you should call it with 4:

```
int SONG_COUNT = 4;

nextSong = Random.Range(0, SONG_COUNT);

```

The rest of your issue is that: 0 and 2 got lucky :)

---

I'm not sure there is something in Unity that would allow you to have something like that, but you could program it yourself: a "random bag".

The idea is that you put all of your "songs" in a "bag", pick one out (at random), use it but leave it out of the bag. Do this until there is only one left. Do it again, but keep the last one you've picked out in your hand, and put back all of the others back in the bag. The next time you need a song, pick it from the bag, then put back the previously one used (that you did not put back in the bag). Rinse and repeat.

The idea is that you'll use *all* of your songs before one can be repeated. And you keep the last one out before re-starting to use them to make sure that you'll never get the same some twice in a row.

---
Tags: unity, c#, random
---


# Question
Title: ECS component dependencies / sharing and cache locality
I have been trying to wrap my head around how ECS works when there are components which are shared or dependent. I've read numerous articles on ECS and can't seem to find a definitive answer to this.

Assume the following scenario:

I have an entity which has a ModelComponent (or MeshComponent), a PositionComponent and a ParticlesComponent (or EmitterComponent).

The ModelRenderSystem needs both the ModelComponent and the PositionComponent.

The ParticleRenderSystem needs ParticlesComponent and the PositionComponent.

In the ModelRenderSystem, for cache efficiency / locality, I would like run through all the ModelComponents which are in a compact array and render them, however for each model I need to pull the PositionComponent. I haven't even started thinking about how to deal with the textures, shaders etc for each model (which will definitely blow the cache).

A similar issue with the ParticleRenderSystem.. I need both the ParticlesComponent as well as the PositionComponent, and I want to be able to run through all ParticlesComponents in a cache efficient / friendly manner.

I considered having ModelComponent and ParticlesComponent each having their own position, but they will need to be synched every time the models position changes (imagine a particle effect on a character). This adds another entity or component which needs to track and synch components or values (and potentially negates any cache efficiency).

How does everyone else handle these kinds of dependency issues?

# Answer
Reducing cache misses doesn't need to mean getting rid of them entirely, so we do need to be wary of "making the perfect the enemy of the good enough"

After all, the absolute worst performance your game can have is a game that never runs at all because you're still working out every detail of the best possible ECS.

If you store all your mesh rendering components contiguously in one array, and all your transforms contiguously in another, then you can expect the bare minimum of cache misses from the former when iterating over it in order. Awesome!

Now, you could still get cache misses when looking up the corresponding transform — say, due to the ordering or your entities, you have a cluster of transforms corresponding to rendered meshes, then a cluster corresponding to physics triggers with no mesh, then back to mesh-havers again. You'll probably take a cache miss hopping over that gap, but that's still a fair shake better than a cache miss for every component strewn randomly through memory. It doesn't have to be perfect to be worthwhile.

Also, since your transforms are likely small and frequently used by many systems, you have a decent chance that some of the ones you need are still hanging out in one of your cache levels from a previous step, even if your lookups weren't perfectly contiguous & pre-fetchable on this pass.

So, try the simplest version that makes sense to you, and profile it on some imitation data mirroring what you expect common use cases to look like. See if you still have more work to do to shave down the cache misses even further, or if other parts of your code are actually a bigger problem in practice (or maybe it's all performing up to your targets already and you're done!)

See also this recent thread about approaches to sorting components to minimize gaps when iterating
> 4 votes

# Answer
Cache coherency is important, but it's not the be-all, end-all of everything.

It is in the general case *impossible* to arrange for your code to provide maximally-coherency access to all the necessary data for *everything* that needs some data. You can do it for small, simple projects, but as things get complex you start having to do tricks like duplicating data or compressing it, and that starts to cancel out some of your coherency gains.

You're generally only going to be able to make a subset of your update processes "perfectly" cache-coherent. You should profile to determine which ones are the most likely to benefit from doing so, based on your game's actual access patterns and distribution of objects, and arrange the data accordingly. Everything else will have to settle for being less-than-ideally cache-coherent, or simply not that coherent at all.

Optimizing for cache coherency is usually more about focusing on the data access patterns, which is often at odds with dogmatic adherence to classification (with both "traditional OO" and "ECS" approaches).

Since position is generally small, it's a reasonable candidate for (effective) duplication: you could consider an approach where the models and particle systems have their own local position, which is an *offset* from the real position. You can process the arrays of models and arrays of particle systems in that local space without having to pull in a shared position from elsewhere until a later stage.

But at a higher level I'd consider simply not worrying about the cache impact too much here. Yet. Both of the systems you're worried about are render-related, so "all of them in one big array" is perhaps *not* the best storage mechanism anyway. You're going to want to do a lot of culling and other kinds of visibility rejection on a lot of these, and that results of that rejection may shuffle the interesting set of of objects around quite a bit, unrelated to their original positions in the array.

Similarly you're going to want to group them around efficient use of actual rendering resources (avoiding state switches, sharing resources where possible, et cetera), which also may imply a different data structure than an array. And you note that you're not even sure what you're doing about "textures and shaders" for each model, which suggests you're not feature-complete there.

Certainly there is cause for concern about having to do make refactoring after the fact if you *really* muck up the design of a system. But I would not let that prevent you from first making the system *work*, with all the features you want. Once it works and does everything you want, then you can make it fast, because you'll have a better idea of what you requirements and constraints actually are.
> 3 votes

---
Tags: game-design, entity-system, entity-component
---


# Question
Title: Having 3D material properties depend on shader
**Disclaimer: I apologise if this is somehow a duplicate question or is unclear.**

I am in the process of writing a 3D scene renderer/editor in C++ using the OpenGL specification. It is actually going surprisingly well considering my past experience (all but none) however I have hit hurdle in designing the way materials work. First, this is how they work now:

Materials have a diffuse/albedo map, a normal/bump map, and a specular map. They also have a diffuse/albedo colour, and a shininess value for when no specular map is provided. This works fine and all however I noticed Unity's material's properties depend entirely on a shader. This is pretty much what I want as this is wonderfully flexible.

I know you can get a list of a shader program's GLSL uniforms as described here but I am struggling with what my Material class should be looking like. Do I have each material hold a map of textures, colours, floats, with the keys being their GLSL uniform name? Or is there a nicer more elegant way? The reason I am against this is because I wouldn't know how to organise the properties in a GUI when all I am given is a uniform name. For example I might have multiple diffuse or specular maps, and I would like to arrange these in a specific manor.

Please let me know if this is an awful question, or if I could improve it in any way. My brain hurts right now.

# Answer
> The reason I am against this is because I wouldn't know how to organise the properties in a GUI when all I am given is a uniform name. For example I might have multiple diffuse or specular maps, and I would like to arrange these in a specific manor.

If you're interested in following Unity's example, then it's worth looking at how they do it.

Unity's ShaderLab files contain not just the shader code that's compiled for your GPU, but also mark-up describing how the engine should treat materials that use this shader. Details like:

* which shaders to use for various passes like shadow casting, deferred G-buffer population, forward lighting etc...
* how to group & sort geometry using these passes (eg. transparent stuff in its own sorted queue)
* what blend, stencil, and depth modes to use
* how to switch between shaders based on level of detail ranges

It also includes a dedicated section of mark-up for the GUI representation of the shader in the Unity editor:

```
// properties for a water shader
Properties {
    _WaveScale ("Wave scale", Range (0.02,0.15)) = 0.07 // sliders
    _ReflDistort ("Reflection distort", Range (0,1.5)) = 0.5
    _RefrDistort ("Refraction distort", Range (0,1.5)) = 0.4
    _RefrColor ("Refraction color", Color) = (.34, .85, .92, 1) // color
    _ReflectionTex ("Environment Reflection", 2D) = "" {} // textures
    _RefractionTex ("Environment Refraction", 2D) = "" {}
    _Fresnel ("Fresnel (A) ", 2D) = "" {}
    _BumpMap ("Bumpmap (RGB) ", 2D) = "" {}
}

```

Here each line starts with an identifier corresponding to the name of the uniform in the shader code. Then in parentheses there's a friendly/descriptive name to display in the GUI, and an annotation of the variable's type and the GUI widget to use to populate it. Lastly there's a default value to use for initializing new instances of materials using this shader.

This way your code doesn't need to be "smart" and infer which variables should be exposed in your editors and how — the shader developer can tell it exactly what it should do. They're free to hide some uniforms that should be constant or set from other sources, or change the names/widgets/order to whatever they think will be most intuitive for users of the material.
> 1 votes

---
Tags: unity, opengl, c++, shaders, materials
---


# Question
Title: What are the advantages of putting cheat codes into a game?
Some games have cheat codes in them, but I'm not sure I want to add some to mine because I fear they'll ruin the game by making it too easy to beat.

What would be the advantages of putting cheat codes into my game?

# Answer
One major feature is that they make debugging easier.

If there's a broken puzzle door that's not unlocking, and you can bypass it by clipping through the walls, or skip past some tough combat with invulnerability and an insta-kill weapon, or shortcut the economy grind by giving yourself infinite money to make sure the last-game purchaseables all work, you've saved yourself a lot of time! Being able to manually spawn an object or character you need to test on demand, rather than finding them organically in the world, can be another huge time-saver.

Without these ways to break the rules, then if the rules themselves aren't working in one part of the game, you can be blocked from testing everything else in the game that depends on or comes after the glitched part (something we call a "walkthrough break," one of our highest priority classes of bug)

This is especially important on large teams where even once you find a bug and someone is actively working to fix it, other developers and testers can be blocked from doing their work, massively slowing down development. Being able to cheat around small issues gives some insulation against this kind of deadlock.

Here's a tweet I spotted today from @Ed\_dV that illustrates this nicely (click through for video):

> Made a little floating window with all of my debug tools, cheat toggles, time of day slider etc. I can't believe I didn't implement cheats earlier - noclip/fly is vital in the early bug-ridden days.

(Of course, you must still follow-up with cheat-free playthroughs whenever possible, to make sure it's not just the cheated version of the game that works)

Once you've put in the work of developing these cheats, there's often little to no cost to leave them in for players, accessible by a secret key combo, cheat menu, or debug console - as long as the game is single-player so they can't be used to interfere with other players' games.

These codes can be a delightful easter egg for players - how many times have you tried entering the Konami Code on a game or website, just to see if it would do something? A lot of us have fond childhood memories of no-clipping through walls in DOOM or giving ourselves all the weapons in GTA, or spawning so many rings and springs in Sonic the Hedgehog that the framerate stuttered. :)

If you give out the cheat codes in-game as rewards for solving difficult challenges, it's an impactful prize that's reasonably cheap to implement, compared to giving the player a new ability or item that needs to be balanced against the rest of the game. With cheats, there's a tacit understanding that it's *allowed* to break the balance or fiction, in an opt-in way. And it lets players feel elite, entrusted with secret knowledge (which they can share with their friends for social cred too).

Lastly, these can provide additional accessibility for players who, for medical or other reasons, might not be able to get to all parts of your game on their own otherwise. If it's the difference between a player enjoying a lower-challenge version of my game than I'd originally intended, versus not getting to enjoy my game at all, I'd rather offer them that lower-challenge version, to the extent that they want to use it.

And for the most part, cheats don't negatively impact the players who dislike them. Players are very good at challenging themselves - for example, opting into difficult "Ironman" or "Nuzlocke" play styles even when not enforced by the game's rules. So players who want a difficult experience generally don't use or even look up the cheat codes.
> 203 votes

# Answer
Yes, you totally should have cheats in your game.

1. **Replay value!** Having all weapons with infinite ammo and invulnerability might make level 1 far too easy, but it can also be a lot of fun when you already beat the game regularly.
2. **Dealing with bugs!** It creates a possibility for the player to work around game-breaking bugs. Let's say there is a very obscure bug in your 120 hour RPG game which, if triggered, prevents the player from completing the main storyline quest. They ask about it on Gaming.SE. There are two answers: "Sorry, that's a known bug. Reload an old save. What, you have no old save? Too bad, then you have to restart the game all from the beginning." and "Yeah, it's a bug. Press `~` to open the console, enter `SETVAR QUEST_7457_COMPLETED 1` and you can continue playing". Which answer would have a better chance to get accepted? Here is a literal example.
3. **Accessibility!** Not all gamers are equally abled. Think about players who have disabilities which impact their motor skills, hearing or seeing. While your game might simply be "hard but fair" for the average gamer, it might be completely unplayable for any people with disabilities. Cheatcodes might give these players a way to level the playing field and also enjoy your game.
4. **Marketing!** Cheatcodes give players something to talk about. They can spread the cheatcodes on social media, on articles and among their social circle. They also can be used to create hilarious Let's Play videos. The games people talk about are the games people want to play.

And all that for a feature which usually does not cost you a lot of money to add because you usually add them anyway for debug purposes.

Regarding your fear of breaking immersion and making the game too easy: Players are fully aware that cheatcodes are not the way the game is meant to be played. They understand that using a cheat can harm their game experience. They will only use them when they think that the game is more fun that way. And when it turns out that the cheatcode breaks the game, they are aware it's their own fault they cheated and will disable them again.

An exception are of course multiplayer games. You don't want any player to ruin the other player's fun with cheating. But even multiplayer games can obtain a lot more variety if you have cheats which can be enabled by the server admin and apply to everyone equally. Reducing the gravity in a first person shooter, for example, adds new navigation paths to the old maps and thus completely changes their game experience. The game experience might not necessarily be *objectively better*, but it is *different*. And differences in gameplay are what creates long-term motivation.
> 90 votes

# Answer
What's most important is that the players enjoy themselves playing the game, even if it breaks "your game". Showbiz is about the audience's enjoyment.

Hiding the cheat codes rather than putting them right in the option menu is a compromise between allowing some players to adjust the difficulty while at the same time officiating the game's original vision of "how it should be played" by putting a small obstacle to enabling the cheats.

Some cheat codes can also be created just aesthetic for entertainment purpose (easter eggs) and some cheat codes can be created to actually make the game more difficult.

But there are more "practical" reasons than simply adjusting the game difficulty:

* Gaming magazines want something to entice players to buy their products (magazines and **strategy guides**) such as a list of cheat codes or passwords,
* Game reviewers need the cheat codes so they can **skip ahead and write their reviews** without spending too much time on the difficult or **grinding parts**,
* Testers and QA need them for basically the same reasons game reviewers use them but even more so (e.g: infinite energy so a tester can properly **test** the wall collisions in a level **without dying and wasting time dodging enemies**),
* You get additional **word-of-mouth marketing**; it gives players something to talk about between themselves.
* Publisher may **require** you to put cheat codes in the game for all those reasons.
> 22 votes

# Answer
Keep in mind that "cheat codes" don't necessarily have to make the game easier. You can have "cheats" that do cosmetic changes, like making all the enemies have huge heads or making your gun shoot paintballs. They could make the game harder, by making enemies tougher or move faster. Not every cheat code has to be unlimited ammo or God Mode. Adding this type of cheat to a game provides some variety for players who are getting tired of the normal game mode.

Additionally, not all cheats have to be readily accesible. Cheats can be a reward for accomplishing certain things in the game, further adding replayability. This ensures that players will experience the game "as intended", and will only be able to use the cheats after becoming familiar with the regular game.

My frame of reference for this answer is the classic N64 game GoldenEye 007, in which cheats are unlocked by beating a level under a time limit. These cheats can make the game easier, harder, or just different. I know I spent many, many hours just unlocking the cheats. To be honest, I don't think I actually played with the cheats on for nearly as many hours as it took me to earn them!
> 21 votes

# Answer
Once upon a time, I played a very fun game called Kittens, by bloodrizer. It was super fun. It's an incremental game where your kittens collect catnip and also take over the galaxy (as tends to happen after consuming catnip.)

There was a problem though - I'm a busy guy. A wife, two kids, a demanding job, numerous volunteer activities. I couldn't actually be there when I needed to for max efficiency. So I found a creative solution - I kept the game on pause the entire time and created javascript functions to fast-forward my time and essentially play my game for me, at least for most automated decisions like spending resources when they get near capacity, etc.

I shared my code, and while the creator couldn't do anything to stop it, she certainly wasn't going to support my position. She considered it cheating. I fundamentally did not see it as cheating - I simply found, and this is key, `a different way to experience the game`. My enjoyment from the game was in figuring out the maximum efficient way to play it. It wasn't the progress I wanted, it was the zero tick waste.

Cheat codes allow your users to experience the game in different ways. Playing Quake 1 on `godmode` and `noclip` was super fun. It doesn't take anything away from the game unless a user wants to - and it's their fun that you want, so don't try to limit it. If people want to enjoy the game as you released it, they will simply play without cheats.

Naturally, this implies they can't hurt others. If I want to play multiplayer, either we all get cheats or no one gets cheats. And really, make it no one gets cheats because multiplayer godmode just seems boring after a few minutes. Or maybe it's not, who knows. Test it - go nuts. HAVE FUN.
> 13 votes

# Answer
Something not touched on by others, is that adding cheat codes also allows players greater agency in the game, as they can play in a way they find fun, without it being the "intended" way. The Sims is a good of this for the "casual" crowd, in that the money cheats are mostly universal; if you've played one The Sims game, you know the code, and how to access it. The game suddenly evolves from a "life simulator" to a House Designing game (Which is ironic, given that, that is what the "game" was initially).

I think GTA V, is a more action oriented example. Various cheat codes allowed the early modding, from my understanding, which allowed people to come up with crazy new activities. I also imagine many of the stunt jumps shown on Youtube, are initially setup using cheat codes (or other forms of hacks), to allow a fast reset and new try. Suddenly, you have a fun activity that's sort of new (They do have stunt jumps, yes, but many of the ones shown on the 'net are new and crazy ones)
> 4 votes

# Answer
As a game hacker, the existence of cheats in a game deters people like me from reverse engineering your game to manufacture cheats of my own. Take, for instance, a game like Skyrim, which allows a player--via the in-game console--to do just about any and every generic type of cheat: health, money, ammo, attributes, levels, etc.

So, if people reversing your game doesn't appeal to you, then adding cheat functionality in yourself is a good way to deter that. On the other hand, *not* adding cheats can be a good way to gauge how drawn people are to cheating your game in the first place. That data can be valuable on its own merits, provided you're interested in it.
> 3 votes

# Answer
"Cheat" codes can have two main purposes:

* Easter eggs, which allow cool stuff in the game, like changing a character skin, game speed, difficulty etc. This is mostly just for fun and to improve the replay-ability of the game, which used to be part of the magazine review rating back in the day (before the internet). These eventually evolved into "unlockables", and then into downloadable content. This is 99% of cheat codes now.
* Unpublished features, which while cool, were useless, too powerful, or just broken, and so were never part of the final game, though remained in the source code. This came about because games used to be made on chips, to be put in cartridges for consoles. Adding or removing data from these chips was expensive, and source control was virtually non existent at the time, so codes were used to enable or disable features. Due to deadlines, some of these features were never officially published, but remained on the cartridges. Later, these codes got leaked, and people started messing around with them. Nowadays this is only possible on the pc, where modding is possible via scripts and command lines, to gain access to, and change, the game state in-memory.
> 2 votes

# Answer
Cheats could be also very helpful for presentation purposes: e.g. you want to show key points of your game quickly, without having to play through all the tough parts. This is especially helpful, if your game is hard to play and you won't bore the public with a lot of death, before you come to the interesting part.

In this case you can decide, either to code some additional user interface with buttons, that allows you to "teleport" yourself to the interesting part of the game, or you implement this game mechanic in the old-style way, using e.g. special key-bindings.

You should of course remember to remove this mechanics when you decide to release. Alternatively you can also reuse them, if you add to your game "story-mode"-difficulty, that allows you to skip the hard parts. But this is up to you to decide.
> 1 votes

# Answer
Most of the cheats and cheat codes that are put into games are for legacy reasons. Long before we could just Google or YouTube how to open a door / defeat the boss / get to the end, a player who weren't good or patient enough to do these things would usually give up and not play the game any more. Putting cheats into them made it so that any player could complete the game.

These days they are still put in but much less frequently. You're more likely to find an Easter Egg than too many cheats.
> -2 votes

# Answer
In many strategy games I would use money cheats or unlocking cheats, to find the most optimized gameplay strategies. So, when I play the game legit with no cheats, I know the correct pathing and placement strategies so I am not disadvantaged late game.
> -2 votes

# Answer
I would say that adding cheat codes is to some degree useful if you cannot beat the game or if you get stuck. That is a pretty good reason to put cheats into a game. However, I've actually seen cheat codes go a bit further.

In one game engine I'm a bit familiar with there is a function that takes in some ascii string and will execute it as if it were compiled code. I think it was put in as a means of implementing lambda expressions if you've ever heard of the term. Regardless, someone decided to be a bit clever and put in a box into their game that you could enter such code into. The nice thing about it was that you couldn't just cheat the game with it. You could also load in external scripts, code up your own enemies or bosses, and just make fun stuff to add to the game. So I would argue that for games that are more action-based like platformers or general adventure games that cheat codes can be a fun way of having a sort of "post-game-content" feel. Someone might make a cheat code (if your system is sophisticated enough) that lets you fight some boss battle in the overworld rather than a dungeon or other location it was fought at. Some people find such a "mod" interesting. Furthermore, if there are cheats to give you infinite lives or health, some people might like that as a convenient way to just explore once they finish the game and just want to "check things out".

Of course, there are the gameplay advantages but I don't think cheating to give a player a handicap isn't the only purpose. After all, if something is too hard there are more fluid ways to make it easier if they successively lose (such as something appearing to let them skip that mission with a penalty of not completing it on the initial pass or something) or just get tired a section. Cheat codes shouldn't be an excuse to not cater the game to varying levels of skill, but sometimes it is just fun to run around shooting 20 bosses at once in the overworld while riding in a mech suit\*.

However, there is such a thing as too many cheats or going a bit too far. I'll elaborate on that example. See the following screenshot from the game.

You can enter literally any line of code that is valid in the engine it was made in. That's a serious problem though as it can exploited as a security breach. In lamen's terms you better not let anyone trying to break into your computer gain access to that thing because then they pretty much own your computer. Granted, in that case they'd already need to be using your mouse and keyboard so it's a bit esoteric of a way to break your PC, but irregardless similar things can occur. Hence, I would warn one not to make a system too advanced because then it might become a means of transmitting viruses hidden in mods or whatever.

Just don't go overkill or at least don't give cheat codes access to file input and output arbitrarily.

---

\*I've never actually tried doing that.
> -2 votes

# Answer
To be honest, I have rarely used cheat codes - apart from some bugs, that I have encountered, but it was only when I was playing a game soon after a release. Afterwards, when they have already patched the game and fixed the bug, I very often went through the mission again, so I'm not labeled a "cheater" by myself. Also, if somebody has some disabilities and still want to play a game, cheats may turn out to be very helpful. For example I have a friend, who was playing GTA:SA with a broken arm. Of course he couldn't play for too long and his mouse movement was heavily limited back then, but he still wanted to play it because all of his high school buddies were talking about it, so he had to use cheats - of course he never told anyone about it except for me as I was his closest friend back then. So yes, cheats should be included in every single game, you can't even imagine how helpful they can become in this situation and after all, it's optional and up to you whether you use them or not, so I don't see anything wrong with them being implemented. Rather than that, I would prefer game developers to make harder games - with cheats included for people, that simply want fun or are unable to finish the game, but without forgetting about old-school gamers, which are used to spending a whole day grinding one mission ;)
> -3 votes

---
Tags: game-design, game-mechanics
---


# Question
Title: What is the little dot/icon at the center of the screen in an FPS game called?
So I am developing a game and trying to find one of those to use, but I don't know what to search for. If you don't know what I am taking about, look at these examples:

What are these called?

# Answer
> 121 votes
"Crosshairs" or an "aiming reticle," usually. Probably also "aiming dot" and similar variations.

# Answer
> 44 votes
In addition to what Josh Petrie mentioned: if you're looking for more advanced ways to aim weapons, the center dot in your bottom image is also called a "pipper" in real-life applications.

This especially applies when some device is actively predicting where an arcing projectile will impact, like a bomb or grenade, instead of simply showing which direction it will go when fired/thrown/dropped.

Aircraft HUDs combine pippers and reticles to convey extra information about complicated firing solutions, as shown in this example:

*Continuously Computed Impact Point Reticle*

So in your third image, the circular arcs are the reticle, while the center dot is the pipper.

# Answer
> -1 votes
That's usually called a crosshair. Also they're probably the easiest texture to make yourself, you don't need to find one online.

---
Tags: terminology, first-person-shooter
---


# Question
Title: Procedural sidescroller world gen algorithm by seed
I'm trying to recreate a procedural side-scroller world gen algorithm by using a seed and I find my self stuck trying to solve a particular problem.

Seed generation applies very well with voxel-like games, but it seems slightly less suitable to generate randomly placed sprites with differing widths for sidescrollers

Here's a picture explaining the problem:

Assuming I load the game at screen-2, I'd be e.g. between coordinates 100 and 0, and the seed function would tell me that between coordinates 100 and 0 there's the sprite of a big block of mountains to render, whose center lies in the coordinate interval \[0, 100\] ( the center of the sprite is the pink dot in the picture)

assuming I'm loading the game from coordinate 300, as is the case in screen-1, a seed function wouldn't be able to recognize the presence of a mountain sprite there, even though part of it is still visible in the interval between e.g. \[250, 350\]

A straightforward solution would be to sample from the seed function the interval including the biggest-sized object in the game, which is of course highly inefficient given many objects only cover a fraction of the screen.

How is this type of problem generally solved? Are algorithms based on seeds unsuitable for this particular project? If this is the case, what could be a reasonable alternative?

# Answer
You'd solve this the same way as you do in 3D.

In 3D games with procedurally generated landscapes, you can often see a distant mountain that's located in a different generation site than the one you're in. So, just as you said, you need to sample the procedural generator function for adjacent areas.

This doesn't become problematically inefficent, because we don't need to sample every adjacent millimetre.

Instead, the world is divided into buckets or chunks of fixed size. Given a position in the world, we can determine which chunk it's in by dividing & flooring the position. Then find the immediately adjacent chunks by adding or subtracting 1.

Each chunk spawns content only inside its bounds. If your maximum object size is smaller than the chunk size, then you only need to check one chunk outside your visible bounds in each direction to ensure you've spawned all content that will be visible to the player.

For a case like you showed, that might be as few as 2-3 chunk evaluations to ensure you can show everything that's visible in a given screen. Not too inefficient at all. :)
> 2 votes

# Answer
If you know your maximum width of sprite -- then you can check for the presence of any sprite between your screen.X - maxSpriteWidth to screen.x + screen.width.

If the scale of your objects is truly gigantic (like, it includes mountains that are miles wide as well as small things less than a meter in size), then you could use a multi-level data structure that separates objects by size: "Find all big things within X miles", "find all medium things within X meters of the screen boundaries", "find all small things within X centimeters of the screen boundaries".

Regarding the actual question of using seeds for the generation part -- generally seeded iterated functions like your usual `random` function work better when you're generating everything up front -- if you're on-the-fly generating "what is the position of item X" or "is there an item in this region R" then it tends to be easier to use a hash of the relevant data.
> 1 votes

---
Tags: game-design, algorithm, software-engineering, procedural-generation, side-scroller
---


title: Coroutine doesn't work

text:
# Question
Title: Coroutine doesn't work
I've been trying to make this work for days and I can't figure it out. I have a code, attached to an enemy prefab, that should display an image a couple seconds after an enemy spawns (this is to show the player it has been attacked). I don't get an error in the console, but it doesn't work either. This is the code:

```
public class enemyAttack : MonoBehaviour {

public float time = 5;
private IEnumerator coroutine;
public Image image;
private float t = 5f;

void Start ()
{
    image.enabled = false;
    StartCoroutine(playerIsAttacked (time, image));

}

IEnumerator playerIsAttacked (float t, Image im)
{
    im.enabled = true;
    yield return new WaitForSeconds (t);

    StartCoroutine (playerIsAttacked (t, im));
}

```

}

Thank you in advance for the help.

# Answer
What exactly "Doesn't work"? I assume what you mean is "the image starts off as visible from the beginning, but I want it to be invisible and appear 5 seconds later.". This is because you've enabled the image first (`im.enabled = true`), and then wait for 5 seconds (`yield return new WaitForSeconds (t);`):

```
im.enabled = true;
yield return new WaitForSeconds (t);

```

You probably meant to wait for 5 seconds first, and then set im.enabled = true afterwards.

Also, unless you want to run the code again every 5 seconds after that, you shouldn't call `StartCoroutine` again inside `playerIsAttacked`.
> 0 votes

---
Tags: unity, image, coroutines
---


# Question
Title: How can I read values from a running instance of an existing game?
I play an indie flight simulation game in Windows. I want to add a specific feature by means of creating a third-party add-on.

This apps will "link" and gather current altitude and position data from the game. My program will play sounds during certain altitude and airplane configurations (it's called GPWS).

I have seen the same thing done in an online RPG game where an external program counts damage dealt in the game (which requires peeking at the game's variables), so I think this is very possible.

My question is:

1. What is this data-gathering called? I googled many terms like hijacking or linking but the result is not what I meant.
2. How do i create program like this? I don't mind if its in other languages like Java or Visual Basic, but my main experience is in C++.

# Answer
The least brittle strategy, as mentioned in Ilja's answer, is to use the game's own modding interface.

As to the question in the title, there are OS-specific APIs to read another processes memory like ReadProcessMemory and ptrace. C++ is one of the better suited languages for interfacing with native OS APIs, so you're in luck with language choice.

Without knowing the specifics, It's hard to tell what the other programs you mention are doing exactly -- I imagine an easy way to get damage values in an RPG is to sniff network packets instead of trying to locate memory locations, but that probably wouldn't work for a single player flight simulator.

Keep in mind that the address of a particular variable in the memory space of a process is not always fixed and can change from run to run. You can use strategies like scanning for known values to help locate the exact address, but it may help to take a look at how players use tools like CheatEngine to scan for the correct addresses.
> 1 votes

# Answer
One of the easiest way to access 'in-game-variables' is through some **public API** (Application programming interface) which this game provides. Not every game provides a public API: the bigger the game is, the more likely this will provide a (good documented) API and vice versa.

The game could also be simply not-modifiable, if game developers don't like user to manipulate in-game data. Or on the contrary, developers could offer some **modification toolkit** for the game, that allows you to create in-game-content in more simple way.

So in your example with indie-game I wouldn't expect that there is some documented public API or modification toolkit available. But if you know that it's possible to modify your indie-game in some way, then I would search for some additional information about it (i.e. at game forums, search Google/YouTube for tutorials etc.).

The other way to access all game variables is through **memory modification**, which you can achieve with some third-party programs, that can interpret memory one or another way (i.e. ArtMoney). But this is more like hacking, not modification that you wanted to achieve.
> 0 votes

---
Tags: c++, modding, memory
---


title: LibGDX player movment

text:
# Question
Title: LibGDX player movment
I'm working on a project in LibGDX. It's a 2d platform game; you can say it's like Super Mario.

So this is how I move my player to the right:

```
if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)){
    player.b2body.applyLinearImpulse(
               new Vector2(0.1f, 0),
               player.b2body.getWorldCenter(),
               true);
}

```

When I release the key, the player is still moving a bit. (It still has a "Linear Impulse" force on its physical body, I think).

How can I make it stop?

My question could be simple as: What is the best way to move a physical body on LibGDX in one direction while holding a key. When I release the key, the body stops immediately.

***I have tried with "setTransform" and it's causing issues when the body is touching other objects - plus the shape comes "before" the rest of the game in the screen (you can see it on debug)***

Thanks.

# Answer
> 1 votes
You can set linear velocity when you release the movement key. It's as simple as doing `body.setLinearVelocity(x, y)` then just set the appropriate axis to 0.

Example:

```
if (Gdx.input.isKeyPressed(Keys.W)) {
    // Move forward
} else if (Gdx.input.isKeyPressed(Keys.S)) {
    // Move backwards
} else {
    // Stop moving in the Y direction
    body.setLinearVelocity(body.getLinearVelocity().x, 0);
}

```

---

Modifying your existing code to this should probably fix it:

```
boolean moveRight = (Gdx.input.isKeyPressed(Input.Keys.RIGHT) || JOYSTICK_RIGHT_PRESSED);
boolean moveLeft = (Gdx.input.isKeyPressed(Input.Keys.LEFT) || JOYSTICK_LEFT_PRESSED);

if (moveRight && player2body.getLinearVelocity().x < 3.00f) {
    player2body.applyLinearImpulse(new Vector2(0.15f, 0), player2body.getWorldCenter(), true);
} else if (moveLeft && player2body.getLinearVelocity().x > -3.00f) {
    player2body.applyLinearImpulse(new Vector2(-0.15f, 0), player2body.getWorldCenter(), true);
} else if (moveRight == moveLeft) {
    player2body.setLinearVelocity(0f, player2body.getLinearVelocity().y);
}

```

The change is in the last `else` statement. I changed it to an `else if` statement that checks if you are either:

* Not moving right or left
* Moving both right and left

If any of these two cases are true you should be standing still. The reason your old code did not work is because if the player was moving at max speed `(velocity >= 3)` or min speed `(velocity <= -3)` the final `else` statement would run and stop the player completely.

---
Tags: 2d, libgdx, physics, box2d
---


# Question
Title: Problem using Event Trigger Unity to change bool , but bool keeps setting back to false
OK so I have used the Unity Event Trigger many times to check for on-screen button presses for Android games. One example I have made many times is a left and right arrow button, which moves the character. There is OnPointerDown() and OnPointerUp() methods which i am utilising (or trying to at least!).

So I have a bool called isLeftToggled and its initialised as 'false'. OnPointerDown/Up both link to a method called ToggleButtonLeft():

```
    public void ToggleButtonLeft(){
    Debug.Log ("LEFT TOGGLED" + isLeftToggled);

    if (isLeftToggled)
    {
        isLeftToggled = false;
    }
    else
    {
        isLeftToggled = true;
    }
}

```

That Debug.Log above reads out ok, it toggles between true and false (although puzzlingly the first log i get is 'True').

However in my update method I have it constantly inform me if its true or false, and it is false for every single call.

I verified this because the ship (game character) doesnt turn when I try to use the bool to turn it. If I initialise the bool to 'true' and remove the toggle by comments, the ship turns fine.

I have the Event Trigger on the button game object, I didnt remember if I had to add something else to make it work. But I am fairly sure the button is working, because it always prints the Debug.Log thats inside the method being called by the two buttons.

Any ideas why the bool is 'false' for every frame. Shouldn't my code above toggle it to true whilst the finger is held on the button?

Here is the whole class (nb. i thought about trimming out the irrelevant parts but didnt want to miss something important out so decided to post whole thing):

```
public class Player : MonoBehaviour {
float rotationSpeed = 360f;
float currentThrust = 0f;
float thrustDecay = 0.02f;
float accel = 0.25f;
float maxThrust = 150f;

float thrustAngle, prevThrustAngle;
float maxTurningThrust;
public GameObject laserStartPoint;
float laserFireRate = 0.5f;
private float laserFireTimer = 5f; // the 5 is a random amount just to make sure no delay at the beginning

public GameObject laserPrefab;

private List<GameObject> lasers = new List<GameObject>();

private Collider gameArea;

private GameObject afterburner;
public GameObject explosionPrefab;

AudioSource audioSource;
public AudioClip laserSound, deathSound, deathExplosionSound, thrusterSound;
float deathWaitTimeBeforeDestroy = 2f;
bool isDying;
GameObject shipModel;

private bool isLeftToggled = false, isRightToggled;

void Start () {
    isDying = false;
    gameArea = GameObject.FindGameObjectWithTag("GameArea").GetComponent<Collider>();
    maxTurningThrust = maxThrust * 0.012f;
    afterburner = GameObject.FindGameObjectWithTag("Afterburner");
    afterburner.SetActive(false);
    audioSource = GetComponent<AudioSource>();
    shipModel = GameObject.FindGameObjectWithTag("ShipModel");
}

void Update () {
    if (isDying)
    {
        shipModel.SetActive(false);
        deathWaitTimeBeforeDestroy -= Time.deltaTime;
        if (deathWaitTimeBeforeDestroy <= 0)
        {
            Destroy(this.gameObject);
            GameController.instanceOf.PlayerLoseLife ();
        }
    }
    else
    {
        HandleInput();
        CheckScreenBounds();

        laserFireTimer += Time.deltaTime;
    }

    Debug.Log("is left toggled: " + isLeftToggled);
}

void HandleInput(){
    // activate weapon
    if (Input.GetKey(KeyCode.Space))
    {
        FireWeapon();
    }
    // Rotate left
    if (Input.GetKey(KeyCode.A) || isLeftToggled)
    {

        transform.Rotate(0, -rotationSpeed * Time.deltaTime, 0);
    }
    // Rotate right
    if (Input.GetKey(KeyCode.D))
    {
        transform.Rotate(0, rotationSpeed * Time.deltaTime, 0);
    }
    // activate thrusters
    if (Input.GetKey(KeyCode.W))
    {
        //audioSource.clip = thrusterSound;
        audioSource.PlayOneShot(thrusterSound, 0.25f);
        afterburner.SetActive(true);
        prevThrustAngle = thrustAngle;
        thrustAngle = transform.eulerAngles.y;
        if (currentThrust < maxThrust)
        {
            if (prevThrustAngle != thrustAngle)
            {
                if (currentThrust > maxTurningThrust) {
                    currentThrust = maxTurningThrust;
                }
            }
            currentThrust += accel;
        }
    }
    else
    {
        afterburner.SetActive(false);
        if (currentThrust > 0f)
        {
            currentThrust -= thrustDecay;
        }
    }

    // Move the ship in the direction it was facing at point when thruster button was last pressed
    transform.position += new Vector3(Mathf.Sin(thrustAngle * Mathf.Deg2Rad), 0, Mathf.Cos(thrustAngle * Mathf.Deg2Rad)) * currentThrust * Time.deltaTime;

    if (currentThrust < 0f)
    {
        currentThrust = 0f;
    }

}

void CheckScreenBounds()
{
    if (transform.position.x - (GetComponent<Collider>().bounds.size.x / 2) > gameArea.bounds.size.x / 2)
    {
        transform.position = new Vector3(-gameArea.bounds.size.x / 2, transform.position.y, transform.position.z);
    }
    if (transform.position.x + (GetComponent<Collider>().bounds.size.x / 2) < -gameArea.bounds.size.x / 2)
    {
        transform.position = new Vector3(gameArea.bounds.size.x / 2, transform.position.y, transform.position.z);
    }
    if (transform.position.z - (GetComponent<Collider>().bounds.size.z / 2) > gameArea.bounds.size.z / 2)
    {
        transform.position = new Vector3(transform.position.x, transform.position.y, -gameArea.bounds.size.z / 2);
    }
    if (transform.position.z + (GetComponent<Collider>().bounds.size.z / 2) < -gameArea.bounds.size.z / 2)
    {
        transform.position = new Vector3(transform.position.x, transform.position.y, gameArea.bounds.size.z / 2);
    }
}

void FireWeapon()
{
    if (laserFireTimer >= laserFireRate)
    {
        GameObject tempLaser = laserPrefab;

        tempLaser.transform.position = laserStartPoint.transform.position;
        tempLaser.transform.rotation = laserStartPoint.transform.rotation;
        Instantiate(tempLaser);

        lasers.Add(tempLaser);

        laserFireTimer = 0f;
        tempLaser = null;

        audioSource.PlayOneShot(laserSound);
    }

}

public void Die()
{
    GameObject explosion = GameObject.Instantiate(explosionPrefab);
    explosion.transform.position = transform.position;
    audioSource.PlayOneShot(deathSound);
    audioSource.PlayOneShot(deathExplosionSound);
    isDying = true;
}

private void OnTriggerEnter(Collider other)
{
    if (other.tag == "Asteroid" || other.tag == "Saucer" || other.tag == "LaserEnemy")
    {
        Die();
    }
}

public void ToggleButtonLeft(){
    Debug.Log ("LEFT TOGGLED" + isLeftToggled);

    if (isLeftToggled)
    {
        isLeftToggled = false;
    }
    else
    {
        isLeftToggled = true;
    }
}
public void ToggleButtonRight()
{
    Debug.Log("RIGHT TOGGLED");

    if (!isLeftToggled)
        isRightToggled = true;
    else
        isRightToggled = false;
}

```

}

here is screenshot of unity. I think it sums up the problem quite well, the Event Trigger on the right shows its calling the method in the class I posted above, the log even shows its getting toggled to True when i push the button, but the ship doesnt rotate, and as you see in the log the bool is 'false' on every frame:

# Answer
the answer is that, as JoshPetrie mentioned above, isLeftToggled is an instanced variable. But I am currently creating a new instance of the Player every time it dies. The problem with this is that the Event Trigger on my UI cannot cope with that. It was calling the method in the script (thats why i got the log telling me it was toggling), but of course it couldnt change the variable of the players isLeftToggled bool, because it has never been pointed to it.

The only fix I can think of for this, is to have the Player instanced in the Hierarchy of Unity, so that I can drag that into the Event Trigger. And I'll have to change my code to always use the same instance of the Player.

Unless there is a way to dynamically change the Event Trigger to tell it which Player I need it to connect with (??!?!?)

Anyway, I am past the problem at least. So thanks for those who helped me. Cheers

EDIT: Thanks to the kind help of LegendBacon on the Unity website, he has linked me to this solution for changing the event trigger during runtime: Unity Answers - full answer
> 0 votes

---
Tags: unity, input, touch
---


# Question
Title: Replacing client side vertex arrays with glBufferData
I need to replace client side vertex arrays in order to upgrade to a new version of OpenGL but I'm not sure what the best way to buffer data is now.

What I have is a 2D sprite engine which is using batching to push as many vertices to the GPU (using fixed pipeline functions glVertexPointer etc...) but frequently the batch is only a single quad. Because of how sorting works the buffer needs to be updated every frame (or more).

I need to use glBufferData/glVertexAttribPointer now so what is the best way to handle this case? I can allocate the buffer for glBufferData large enough to hold the maximum size of a batch (which is more than maybe 5000 vertices) so should I just push the old vertex array to glBufferData every frame or use another method? Maybe calling glVertexPointer/glBufferData has the same costs associated with them to copy memory to the GPU so I don't need to worry about it but I'd like to know since I'm still pretty new to OpenGL.

CONCLUSION:

In my simple tests I found calling glBufferData every frame with all vertices (OpenGL 4.1) actually slightly faster than client side vertex arrays (OpenGL 2.1).

Thanks.

# Answer
Basically, you're sending between 4 and 5000 vertices in an array. The time to upload will likely be the same between `glBufferData()` and other methods. The docs for glBufferData() lay it out pretty nicely. You can specify how the vertex data is going to be handled once it's uploaded:

> `usage` is a hint to the GL implementation as to how a buffer object's data store will be accessed. This enables the GL implementation to make more intelligent decisions that may significantly impact buffer object performance.

You don't say how you're drawing things, but I would assume that there's some coherence from one frame to the next. You probably aren't drawing completely different sprites on each frame. So you can take advantage of that by not uploading the same geometry every frame. Only upload the new stuff, or change what has changed. You can use `glBufferSubData()` for that.
> 1 votes

---
Tags: opengl
---


# Question
Title: How can i access animation from animator in unity3D
I want to perform some specific functionalities if my character is in Idle state and IdleUnarmed animation is playing and !anyKeyDown. I do not know how to access that "IdleUnarmed" animation from animator. The code i am using is

```
int idle = Animator.StringToHash("Base Layer.Locomotion.Free Locomotion.Free Locomotion.Idle.IdleUnarmed");
        AnimatorStateInfo stateInfo = anim.GetCurrentAnimatorStateInfo(0);
        if (!Input.anyKeyDown && stateInfo.GetHashCode() == idle)
         {
            if (Time.time > currentTime)
            {

```

But it is not working. Anyone please help me to sort out this issue. Thank you

# Answer
Check out the Animator.Play() function: https://docs.unity3d.com/ScriptReference/Animator.Play.html
> 3 votes

---
Tags: unity, c#, animation, unityscript
---


# Question
Title: How can I center a WebGL window in Unity?
I have a WebGL build for my game, however, I'm getting frequent requests to center the image. Right now it is left justified. How can I center the WebGL game window?

# Answer
You can create a custom WebGLTemplate just change the HTML as documented here. You can choose either one of the defaults or create your own template.

According to those docs you create folder in `Assets` called `WebGLTemplates` and inside that create a new folder for your template like `BetterTemplate`. Inside that put an `index.html` file and any other images, css, JavaScript files you want included with your game.

The index.html could look something like this

```
<!DOCTYPE html>
<html lang="en-us">

  <head>
    <meta charset="utf-8">
    <title>%UNITY_WEB_NAME%</title>
    <style>
      body { margin: 0; }
      #gameContainer { width: 100vw; height: 100vh; }
      canvas { width: 100%; height: 100%; }
    </style>
    <script src="Build/UnityLoader.js"></script>
    <script>
    var gameInstance = UnityLoader.instantiate("gameContainer", "Build/dist.json");
    </script>
  </head>

  <body>
    <div id="gameContainer"></div>
  </body>

</html>

```

Then you pick Edit-\>Project Settings-\>Player from the menus and under the WebGL tab choose your template

Here's an example that provides a custom logo.
> 2 votes

---
Tags: unity, webgl
---


# Question
Title: Unity - Generate Shape based on user's input
I would just like to ask if how can I generate a 2D rectangle shapes based on user's input. For example if he inputs 5, 5 rectangles will be created.

Also. I would like to put a integer attribute on the shape generated. (for example, Shape 1: Value 5f, Shape 2: Value 10f, Shape 3: Value 10f, etc...)

Any help will be appreciated! thank you!

# Answer
> -1 votes
Because your question is not very detailed, there could be a number of ways to accomplish this.

If you are using buttons on the UI and Canvas as your methods of input, simply create buttons labelled 0-9 or whatever, and then onClick of these buttons, call the following function with the respective numbers input into them to specify how many rectangles you want, and at what size.

```
 public void createRects(int numOfRects, float value, float scaleX = 1, float scaleY = 1){

 //Iterate through number of rectangles
     for(int i = 0; i < numOfRects; i++){
     //Create new rectangle
     GameObject latestRect = Instantiate(rectanglePrefab,
     transform.position, transform.rotation) as GameObject;
     //Set Scale and Position
     latestRect.transform.translate(5 * i,0,0);
     latestRect.transform.localScale += new Vector3(scaleX, scaleY, 1);
     //Name our rectangle according the value you wanted to hold.
     //You can literally do anything with this instead.
     latestRect.gameObject.name = "Rectangle" + value.ToString();
     }
}

```

If you want to achieve it using a value that the User inputs via the Keyboard, then you would have to do the following instead:

```
void Update(){
   for ( int i = 0; i < 10; ++i )
   {
     if ( Input.GetKeyDown( "" + i ) )
      {
     for(int r = 0; r < i; r++){
       //Create new rectangle
     GameObject latestRect = Instantiate(rectanglePrefab,
     transform.position, transform.rotation) as GameObject;
     //Set Scale and Position
     latestRect.transform.translate(5 * r,0,0);
     //Name our rectangle according the value you wanted to hold.
     //You can literally do anything with this instead.
     latestRect.gameObject.name = "Rectangle" + r.ToString();
        }
       }
     }
    }

```

---
Tags: unity
---


# Question
Title: How to start a Coroutine in another script?
I did some research about this but what i found was kinda confusing so I didn't actually understand it. Basically I have a coroutine that displays an image after 5 seconds, but I want that image to display 5 seconds after an enemy spawns. I understand that what I need to do is call StartCoroutine in my enemy spawning function, but I'm very new to programming and i couldn't do it, even though it's probably something really easy.

Here's the code that displays the image:

```
public class enemyAttack : MonoBehaviour {

 public Image TargetImage;

 void Start ()
 {
     TargetImage.enabled = false;
     StartCoroutine(playerIsAttacked (5, TargetImage));

 }

 public IEnumerator playerIsAttacked (float t, Image im)
 {
     yield return new WaitForSeconds (t);
     TargetImage.enabled = true;
 }

```

}

and this is the code that spawns the enemies:

```
public class TimedSpawn : MonoBehaviour {

 public GameObject spawnee;
 public bool stopSpawning;
 public float spawnTime;
 public float spawnDelay;

 void Start () {
     InvokeRepeating ("SpawnObject", spawnTime, spawnDelay);

 }

 public void SpawnObject (){
     Instantiate (spawnee, transform.position, transform.rotation);

     if (stopSpawning) {
         CancelInvoke ("SpawnObject");
     }
 }

```

}

# Answer
> 1 votes
Be careful when running coroutines in this manner. Especially lots of them. I agree with user @Jimmy, who left a comment on your question; however, for the sake of pointing you in the right direction and helping you become better at understanding programming and calling functions, I'll detail a solution below.

On your enemyAttack script, add the following code as a function.

```
 public void spawnAttack(){
  StartCoroutine(playerIsAttacked (5, TargetImage));
 }

```

Then, change your TimedSpawn script, to this:

```
public class TimedSpawn : MonoBehaviour {

public GameObject spawnee;
public bool stopSpawning;
public float spawnTime;
public float spawnDelay;

void Start () {
 InvokeRepeating ("SpawnObject", spawnTime, spawnDelay);

 }

 public void SpawnObject (){
 GameObject newSpawn = Instantiate (spawnee, transform.position, transform.rotation) as GameObject;
 newSpawn.getComponent<enemyAttack>().spawnAttack();

 if(stopSpawning) {
     CancelInvoke ("SpawnObject");
      }
   }
 }

```

What's happening here, is that you're creating a function (spawnAttack) within your enemyAttack script which all it does is start the coroutine on the same script. However, because your spawnAttack function is public, it can be accessed outside of this script via referencing.

So in your TimedSpawn script, all you have to do is when you instantiate your new object, you set it to a GameObject within the scope of the SpawnObject function. You then access that GameObject and call the function belonging to it, which happens to be spawnAttack. The spawnAttack function will run, and start your coroutine.

---
Tags: unity, scripting, coroutines
---


# Question
Title: How to read a data from multiple selected text files in unity
This question is based off of a previous one.

How to read a data from text file in unity

But I cant get the code to work for my purpose. I want to be able to choose which CSV files needs to be edited instead of just assigning one file.

Here is the code

private void readData()

```
{
    TextAsset csvFile = Resources.Load("Assets/Resources/Test1.csv") as TextAsset;

    string[] records = csvFile.text.Split(lineSeperater);
    foreach (string record in records)
    {
        string[] fields = record.Split(fieldSeperator);
        foreach (string field in fields)
        {
            contentArea.text += field + "\t";
        }
        contentArea.text += '\n';
    }

```

I want to access the file using a given link and then write to it. but for some reason it keep saying "Object reference not set to an instance of an object" referring to "string\[\] records = csvFile.text.Split(lineSeperater);"

I'm new to coding so it might be missing something silly. but as far as i know it should make sense? as csvFile is given the usl, but the url is not being found when its searching for csvFile.text, but then again, i might be completely wrong.

Could someone maybe help me and guide me in the right direction?

# Answer
Don't neglect to check the docs on Resources.Load:

> The path is relative to any Resources folder inside the Assets folder of your project, extensions must be omitted.

So `Resources.Load("Assets/Resources/Text1.csv")`

should instead be `Resources.Load("Text1")`
> 1 votes

---
Tags: unity, android, ios
---


# Question
Title: How can i display some text information in the middle of the screen in a box?
Something nice to display text.

What i did so far: When the player is pointing with the camera on "Interactable" object it's showing on the object a description text. Then when the player is making left mouse click it will display more information about the object.

The problem is that it's showing the clicked text under the already exist text and not in the middle of the screen in a nice box.

This script is attached to the Player. I'm using two bool variables to check when to display the information: hasDescription and clickForDescription.

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class DetectInteractable : MonoBehaviour
{
    public Camera cam;
    public float distanceToSee;
    public string objectHit;
    public Image image;
    public bool interactableObject = false;
    public Canvas canvas;
    public Text interactableText;
    public ItemInformation iteminformation;

    private RaycastHit whatObjectHit;
    private RotateObject rotateobj;
    private bool hasDescription = false;
    private bool clickForDescription = false;
    private int layerMask = 1 << 8;

    private void Start()
    {
        rotateobj = GetComponent<RotateObject>();
    }

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            clickForDescription = true;
        }

        Debug.DrawRay(cam.transform.position, cam.transform.forward * distanceToSee, Color.magenta);

        if (rotateobj.rotating == false)
        {
            if (Physics.Raycast(cam.transform.position, cam.transform.forward, out whatObjectHit, distanceToSee, layerMask))
            {
                image.color = Color.red;
                objectHit = whatObjectHit.collider.gameObject.name;
                interactableObject = true;
                interactableText.gameObject.SetActive(true);
                interactableText.text = whatObjectHit.collider.gameObject.name;
                print("Hit ! " + whatObjectHit.collider.gameObject.name);
                hasDescription = true;
            }
            else
            {
                image.color = Color.white;
                interactableText.gameObject.SetActive(false);
                hasDescription = false;
                clickForDescription = false;
                print("Not Hit !");
            }
        }
    }

    private void OnGUI()
    {
        if (hasDescription == true && clickForDescription == true)
        {
            var centeredStyle = GUI.skin.GetStyle("Label");
            centeredStyle.alignment = TextAnchor.UpperCenter;
            GUI.Label(new Rect(Screen.width / 2 - 50, Screen.height / 2 - 25, 100, 50), iteminformation.description, centeredStyle);
        }
    }

    public class ViewableObject : MonoBehaviour
    {
        public string displayText;
        public bool isInteractable;
    }
}

```

The second script is attached to each "Interactable" gameobject and i'm writing for each object some information. This is the text i want to display in the middle of the screen or in some position on the screen to display mroe information about the item/object.

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ItemInformation : MonoBehaviour
{
    [TextArea]
    public string description;
}

```

In this screenshot it's when i'm pointing with the camera on "Interactable" object the pointer is turning red and the text description is in white. This is fine and working good:

And this is when pointing on "Interactable" object and then clicking on the mouse left button: What i want is to display the new text information in a nice big box in the middle of the screen with some bigger size of the fonts like in adventure games when you click on item and it's giving you description.

The first white short description should be stay on the object/item the text in ItmeInformation script should be in the middle of the screen like in adventure/quest games.

# Answer
You could serialize a GUIStyle on your inspector, it should be on an object that stays on scene (maybe the same interactable).

```
using UnityEngine;
using UnityEditor;

public class ExampleClass : MonoBehaviour
{
    [SerializeField] private GUIStyle boxStyle;  /// <summary>Your box's style.</summary

}

```

Once serialized, you can explicitly configurate its attributes defined on GUIStyle's API.

Or, you could play with Unity Engine's UI elements, and enable UI panels when you have an interactable on sight. UI elements have a RectTransform, which inherits from Transform, and has additional properties like anchors and pivot definitions, for you to position that UI on the interactable's position, relative to the UI's anchor.

Use Camera.ScreenToViewportPoint to convert the interactable's position to a viewport's (a normalized space)

```
using UnityEngine;
using UnityEngine.UI;
using UnityEditor;

public class ExampleUI : MonoBehaviour
{
    private RectTransform recttransform;

    void Awake()
    {
        recttransform = GetComponent<RectTransform>();
    }

    public void EnableDescriptionBox(Vector3 interactablePosition)
    {
        recttransform.gameObject.SetActive(true);
        recttransform.position = Camera.ScreenToViewportPoint(interactablePosition);
    }

}

```
> 1 votes

---
Tags: unity, c#
---


# Question
Title: How can I make a Custom Inspector display a UnityEvent method selection widget like the Button OnClick Inspector?
I know that UnityEvents display themselves automatically with the default inspector.

But what if you create a custom inspector by extending the Editor class? The fields don't draw automatically since they're overridden by the custom editor.

How can I write my custom Editor class, so that it displays my UnityEvent fields in exactly the same way as the default inspector?

For example, here is the UnityEvent method selection widget for the Button component using its default inspector:

# Answer
> 1 votes
This has worked just fine in my tests:

```
[CustomEditor(typeof(TypeWithCustomEvent))]
public class TypeWithCustomEventEditor : Editor {

    public override void OnInspectorGUI() {
        // Find the property corresponding to the UnityEvent we want to edit.
        var prop = serializedObject.FindProperty("myEvent");

        // Draw the Inspector widget for this property.
        EditorGUILayout.PropertyField(prop, true);

        // Commit changes to the property back to the component we're editing.
        serializedObject.ApplyModifiedProperties();
    }
}

```

---
Tags: unity, gui, editors
---


# Question
Title: How can large terrains be represented in multiplayer games?
To give you a bit of context, I often try and imagine how big games are working, especially networked and multiplayer games. This is how I came to this question: how do big 3D multiplayer games load their 3D, predefined maps? (I am not talking of generated ones, such as in Minecraft, but defined maps that represent, for example, a kitchen).

The most viable hypothesis to me are:

* Some basic map terrain is loaded in a .obj file (with just variations of height and of ground material), and then more data (like trees) is added according to another file, stored in a format like `xml`, which also contains paths to other `obj` files. This techniques therefore allows modifications of terrain, as well as something like serialization to send data to a new client joining (but it's really heavyweight and hard to implement). Finally, you can base player position on which tile they are, and make easier collision & al (for RTSs for example).
* A map containing all data in a single `.obj` file is loaded by all clients, and they are just allowed to move inside it (is this the case in FPSs like Quake?)

But I think both of these techniques aren't optimized enough for commercial or public use. Do you have any idea of how can these games load their map data?

# Answer
> 1 votes
Generally, large maps are stored, loaded and rendered in pieces. This way, only the parts of the world immediately surrounding the player or players needs to be fully loaded and simulated, and the game doesn't waste time or resources on map data that cannot be seen.

If appropriate for the game, level-of-detail techniques can be used -- so, for example a very low-resolution version of a map piece can be loaded up for when that terrain is visible from a large distance (if the player is on top of a mountain, for example). That low-resolution chunk will eventually be replaced by streaming in a high-resolution chunk as the player moves closer to it.

These techniques can be applied to game simulations that occur in these map pieces as well. For example, AI for characters far away may not run as often or may fall back to doing "low resolution" AI processing.

The `.obj` format is very simple, and works well for small games or for developers getting started with model formats. Its simplicity gives it a number of disadvantages in both performance, size, and functionality, however. In practice many games will use a proprietary format for mesh data that more-directly mirror the game's actual runtime requirements for format. This may involve using a different format for terrain meshes than for character meshes as well.

`.obj` may work fine as in interchange format for getting data out of a modelling program, but it's often desirable to convert (offline) the `.obj` data to something more bespoke before using it at runtime.

---
Tags: 3d, networking, maps
---


# Question
Title: Do sprite animations usually run at the same framerate as the game itself?
Just getting into game development and wondering about fps. For example, Binding of Isaac can run at 60 fps, but looking at its sprite sheet, the walk animation is only 12 frames. The game animation definitely doesn't look like its running at 60 fps, but I think the collision, movement, etc. systems are?

I'm working on a game I plan on running at 60 fps, is this a good frame rate for a first game, and how do you fit sprite frames into a higher frame rate? I assume if you have a 12 frame/second animation, you can run each sprite frame for 5 in game frames.

I've seen people talk about issues in running a 12 frame cycle in a 30 fps game, because the ratio isn't a whole number, so it doesn't scale. Will this be a problem if someone wants to run the game at a lower frame rate? Or is the frame rate locked and the game slows down if a computer can't run it?

*Sorry if I'm asking some obvious questions, I'm pretty new to this.*

# Answer
> 0 votes
The frame rate of your game can be a different concept from the number of frames in a particular sprite sequence and how quickly you shuffle between them.

60 FPS as the overall render frame rate target for you game is a fine idea. But when you're animating sprites you might not always want to have a fixed 1/60th of a second pass before switching to the next frame - you may want to linger on certain "high impact" frames, for example, to create a particular visual feel. Or you may want to just evenly linger on every frame enough that a 12 frame cycle takes one second to complete, as you note.

Generally an animation sequence will support the notion of the amount of time to spend on any given frame, somehow. You might then have code that updates the sprite do something like this, *conceptually*:

```
void Sprite::Update(float elapsedTime) {
   timeRemainingThisFrame -= elapsedTime;
   if(timeRemainingThisFrame <= 0.0) {
     // for brevity, only advance one frame every time, but you may want
     // to account for very long frames due to perf spikes that may require
     // you to skip more than one frame.
     currentFrame = (currentFrame + 1) % frameCount;
     timeRemainingThisFrame = frameData[currentFrame].timeForFrame;
   }
}

```

Generally you don't want to fix the rendering framerate, except to perhaps tie it to the vertical blank so you don't get tearing. But you might be running your underlying game simulations at a different framerate (say, 30 FPS for physics).

# Answer
> 2 votes
> how do you fit sprite frames into a higher frame rate?

The trick is to run animations at spritesheet framerate (e.g. 12fps) and run character/entity movements (physics, camera, particles, GUI, etc) at full 60fps.

This way you will save on drawing spritesheets, but perceived animation smoothness will still be high. Especially if you add particle effects, camera panning and other nice non-drawn-animation based effects.

> Will this be a problem if someone wants to run the game at a lower frame rate?

Typical game has display (in a broad sense) and internal state decoupled. So no matter what display pipeline you have (within sane bounds) you still have the same game mechanics working with the same player input.

Generally games try to skip frames and avoid slowing down. Otherwise games difficulty will suffer - players will deliberately slow down their PCs to take advantage of increased reaction times. When skipping frames, animation and movement will look chopped, since you will have to drop some movement or even animation frames. There's no way around it.

---
Tags: 2d, graphics-programming, frame-rate
---


# Question
Title: Where is 'game logic' implemented in component based design?
I have been trying to get my head around using an entity component system for a game. But I am struggling to understand how I should do 'game-logic'.

What I have so far:

1. Components are essentially just dumb data holders, no logic beyond getters and setters.
2. Systems do processing on groups of components. E.g a PhysicsSystem might process all entities containing Transform and Velocity components.
3. Entities are just integers.

My question is, how do I add 'entity-specific' or 'game' logic? For example, I will have an entity which represents the player. How do I go about moving the player entity?

Couples ideas I had, not sure if any are good?

1. Create a 'MovementSystem' which uses a component (e.g PlayerMovementComponent). Then give just my player entity the PlayerMovementComponent. This is basically just a system which only ever processed the one entity... seems a big fudgey.
2. Create a Script or Behaviour component which holds a `std::function` (or maybe could reference a lua script), could then have lambdas which allow unique game logic to be given to entities. This seems to go against the data-orientated approach I’m trying to follow?
3. Create a Player class, have it reference the entity Id then give the player class an update method hooking into the game loop. This update method can edit its referenced entities components before the systems process. This is basically disconnecting myself entirely from the ECS for game-logic... not a fan of this idea (also will make my game loop bloat as more unique entities are required).

Hopefully, I can get some comments on the 3 ideas above and some new ideas or thoughts I can pursue.

# Answer
> 3 votes
Not everything in your game must be based on the ECS pattern you're using and the game logic might be a good candidate not to.

It could be a global script.
Or, as you mention, you *can* implement the logic as a system not to "pollute" your main loop with different classes: this game\_logic\_system, during its update phase, could callback on script(s) or implement the logic in a more hard-coded way, or via plugin, configuration file, etc...

Whichever way you implement the game logic, it has to be *aware* of the ECS: it has to identify (for instance) the player entity (by either a unique-id assigned to it, or by looking for entities with a dedicated Player component as you propose) and most of the logic will result in setting some component properties or calling ES methods to obtain the desired behavior.

# Answer
> 1 votes
All three of your suggestions are fine. Use all of them that fit your needs.

You don't have to (and *should not*) try to shove everything into the "entity component" model. That just creates the same basic shape of problem you have when you shove everything into the "inherit all the things" model: you've just swung the pendulum the other way.

I usually represent the player as a thing that gets a reference to some controlled entity, and recieves actions representing the (human) player's requests from the input system. It interprets those actions according to whatever logic the game needs and makes the appropriate changes to the referenced entity. It's not a "system." It's just what it is. There is one of them (usually), and it just sits in the main `Game` class the whole time.

You could just as well implement it as a component you attach to entities, owned by a "system" that collects player input and feeds it to every component. Letting the player drive multiple entities, if that's what you really want.

Your "script" component might be useful on its own, either to implement this player control or do handle other one-off or game-specific logic that doesn't deserve its own system or module or component or whatever you're using.

---
Tags: c++, entity-system, component-based
---


# Question
Title: Rotate Rigidbody2d slowly for 360 degrees
I would like to perform a 360 degree rotation on a GameObject with rigidbody2d component. You should be able to see the rotation, so I thought of rotating the object 8 times with 45 degrees each around the z axis. So far, one might think that this should be an easy task. But, after several hours, I'm really stuck here.

I tried several code snippets (although not understanding them completely, I must admit):

```
void FixedUpdate()
{
    rigidbodyComponent.MoveRotation(45.0f);
}

```

==\> Rotates the object one time for the desired angle.

```
void FixedUpdate()
{
   rigidbodyComponent.MoveRotation(45.0f);
}

```

==\> Nothing happens.

Could you please give my a hint in what direction (meaning: classes / methods) I should proceed?

Thanks.

# Answer
> 1 votes
`Rigidbody2D.MoveRotation` documentation

> Rotates the rigidbody to angle (given in degrees).

In short, you are setting the orientation of the rigidbody to be 45 degrees over and over again. To rotate it over time, you would need to set its rotation to different values (rather than just a constant 45). Here's a simple example using a coroutine to do what you want, in 8 steps, each step .5 seconds apart.

```
void Start()
{
    StartCoroutine(DoRotate());
}

IEnumerator DoRotate() {
    for (int i = 0; i < 8; ++i) {
        rigidbodyComponent.MoveRotation(45 * i);
        yield return new WaitForSeconds(.5f);
     }
}

```

# Answer
> 1 votes
You may want to post your question here: https://answers.unity.com/

However I think I have the solution.

1. Go to your game object you want to rotate
2. Click Add Component
3. Type Rotate This Object
    * A this script will allow you to rotate the object on any of its 3 axis.
4. Enter 360 in the Z or Y axis, which ever you'd like.
5. Play the scene and you should see it rotate endlessly.
    * If the object drops through the play scene try disabling the "Use Gravity checkbox in the Rigidbody component of the game object.

If you do not have this script automatically in the list of available scripts you may be using an earlier version of Unity under 2017.1. I'd suggest upgrading. Let me know if this helps!

Edit: I forgot you wanted 2D rotation

```
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody))]
public class RotateThisObject : MonoBehaviour
{
    public float z_Rotation;
    public float rot_Speed = 1;

    void Update()
    {
        transform.Rotate(new Vector3(0,0,
             (z_Rotation > 0) ? z_Rotation * Time.deltaTime * rot_Speed
: 0));
    }
}

```

That should work perfectly. I modified the script that came with unity called RotateThisObject. I suggest just copying the code into your own script instead of overwriting RotateThisObject like I did.

# Answer
> 0 votes
Like you said you already have a rigidbody2d attached, so take a look at the following link

```
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    public float speed = 45;
    public Rigidbody2D rb2D;
    void Start() {
        rb2D = GetComponent<Rigidbody2D>(); //Get component attached to gameobject
    }
    void FixedUpdate() {
        rb2D.MoveRotation(rb2D.rotation + speed * Time.fixedDeltaTime);
    }
}

```

Now I am not a 100% certain but if you set the speed too, lets say 45 it should adjust it by 45 degree angle every second. I suggest reading all the info given in the link to get a better idea

---
Tags: unity, 2d, rigidbody
---


# Question
Title: How can i rotate both NPCS facing the door moving to the door and then...?
I need to make some steps.

1. To rotate both npcs but each time running the game they will rotate randomly from another direction. For example the first one will rotate from the right side or left side same the other one.
2. They will facing the door and start moving to the door. Near the door she will open automatic they will wait then they will move through the door.
3. one of the npcs will keep moving and will start random patrolling.
4. The second npc will rotate facing the door from the outside and will do something like locking the door ( I will animate it later he will rotate facing the door wait 2-3 seconds will rotate and will join the first npc and start patrolling too.

This is a screenshot of both npcs each one have a box collider. The door they should rotate smooth randomly and facing and moving to the door the one behind them.

This is the behind the door outside the hall. This is where one of the npcs should start patrolling and the other one wait some seconds facing the door like he is locking the door and then after some seconds to join and start patrolling too.

And this is the hall out side the door and then the hall right and left. They should be patrolling the hall right and left and also the hall with the door. But not getting too close to the door/s so they will not open all the time.

The last screenshot show where they should be patrolling. The left image is the hall outside the door the right image is a door on the front hall on the right and the bottom image the door on the left.

It's like a T

I need some guide how to start it by logic how to do it. I have the scenario in my mind what they should do the 4 steps. But not surw hot start doing it.

The scenario in general is: Two guards(npcs) lock the door from the outside and start patrolling outside.

# Answer
For the rotation you should look at the MoveRotation documentation for unity. This will allow you to smoothly rotate a rigidbody a certain way. You can use a random number to determine which way the will rotate like:

```
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour
{
    public Rigidbody rb;
    public float randRotation;
    float speed = 1.0f;

    void Start()
    {
        randRotation = Random.Range( 0, 1); //0 or 1
        rb = GetComponent<Rigidbody>();
    }

    // fixedDeltaTime provides the same time that FilterUpdate() uses
    void FixedUpdate()
    {
        if (randRotation == 0)
        {
             //Rotate character left
        }else{
             //Rotate character right
        }
    }
}

```

What I recommend for you to take a look at for the patrolling is the usage of a waypoint system. If you want all guard to patrol that is. It basically is an array of points which the guard shall walk too. You can make this random or structured.

I found a good answer on the Unity forum Just to be sure I will copy the code he showed into this answer in case of removal:

```
public class ClassName: MonoBehaviour {

 public Transform[] waypoint;        // The amount of Waypoint you want
 public float patrolSpeed = 3f;       // The walking speed between Waypoints
 public bool  loop = true;       // Do you want to keep repeating the Waypoints
 public float dampingLook= 6.0f;          // How slowly to turn
 public float pauseDuration = 0;   // How long to pause at a Waypoint

 private float curTime;
 private int currentWaypoint = 0;
 private CharacterController character;

 void  Start (){

     character = GetComponent<CharacterController>();
 }

 void  Update (){

     if(currentWaypoint < waypoint.length){
         patrol();
     }else{
         if(loop){
             currentWaypoint=0;
         }
     }
 }

 void  patrol (){

     Vector3 target = waypoint[currentWaypoint].position;
     target.y = transform.position.y; // Keep waypoint at character's height
     Vector3 moveDirection = target - transform.position;

     if(moveDirection.magnitude < 0.5f){
         if (curTime == 0)
             curTime = Time.time; // Pause over the Waypoint
         if ((Time.time - curTime) >= pauseDuration){
             currentWaypoint++;
             curTime = 0;
         }
     }else{
         var rotation= Quaternion.LookRotation(target - transform.position);
         transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * dampingLook);
         character.Move(moveDirection.normalized * patrolSpeed * Time.deltaTime);
     }
 }
 }

```

As for the locking the door I recommend making a state machine for your guards so that you can assign a close door state or something along those lines. Which you then fill with the data you want regarding it closing a door.
> 1 votes

---
Tags: unity, c#
---


# Question
Title: How to identify a Tile without using its name attribute
In the newly added Tilemap system, the `TileBase` and `Tile` have no `tag` attribute and it is then not possible to identify them by anything else than their `name` attribute which is not very practical. It is however said in the documentation of `TileBase` :

> Inherit from this to implement your custom tile to be placed in a Tilemap component.

I guess it can be used to create our own tile system but then I can't find a way to use this new class in the tilemap instead of the basic `Tile` class. How can I use this inheritance to create my own Tiles ?

# Answer
> 2 votes
Tiles only have one instance, you can get these from the tile palette. The tiles inside the tile maps are the same, so if you have a tile instance, you can simply use

```
tilemap.GetTile(position) == tile

```

To create your own tiles, you need to inherit from `TileBase` and override some of the methods (at least `GetTileData` and `RefreshTile`, the latter one should also refresh the surrounding tiles if necessary)

---
Tags: unity, c#, tilemap
---


# Question
Title: Unity - PlayerPrefs.SetString appears to save garbage data
In Unity, I have an InputField calling this method for OnValueChanged:

```
public void SetUsername (string s) {
    username = s;
    print(s);
    PlayerPrefs.SetString ("username", s);
}

```

`print(s);` succesfully prints the typed text, but `PlayerPrefs.SetString ("username", s);` is saving what looks like garbage data. After exiting the game, here's what the relevant line of the PlayerPrefs file looks like:

```
<pref name="username" type="string">ZHNmc2Rmc2FkZg==</pref>

```

`ZHNmc2Rmc2FkZg==` isn't the string I saved...

What's going on? What am I doing wrong?

# Answer
> 4 votes
This happens because Unity does not directly write the string to the PlayerPrefs file, instead, it serializes it into a format which can be saved without conflicting with the XML. For example, it would be bad if you tried to save the string `</pref>`.

This string will appear correctly once loaded with `PlayerPrefs.GetString()`.

I figured this out while writing the question. I hope others can find this useful.

---
Tags: unity, c#, savegame
---


# Question
Title: C# XNA Making a TextBox Appear to input the X and Y coordinates
Okay I'm trying to find a way to not have to hard code in my values for the x and y coordinates. so far I have hard coded these in when you press certain numbers on num-pad it'll move the camera to that area.

```
        if(Keyboard.GetState().IsKeyDown(Keys.NumPad1))
        {
            x = 100;
                y = 100;
            spritePosition = new Vector2(x,y);
        }
        if (Keyboard.GetState().IsKeyDown(Keys.NumPad2))
        {
            x = 200;
            y = 200;
            spritePosition = new Vector2(x, y);
        }
        if (Keyboard.GetState().IsKeyDown(Keys.NumPad3))
        {
            x = 300;
            y = 300;
            spritePosition = new Vector2(x, y);
        }

```

What I'm trying to accomplish is to make a textbox or to be able to input x and y coordinates whilst the application is running

```
        if (Keyboard.GetState().IsKeyDown(Keys.Enter))
        {
            x = 100;
            y = 100;
            spritePosition = new Vector2(x, y);
        }

```

so have something like this but allow the user to change the coordinate values whilst the application is running, when the user presses Enter, of course Console.WriteLine and Readline do not work, so I was wondering how to implement this sort of changes to make it work.

# Answer
> 0 votes
I think what you want to do is to change variables faster while the game is running, so that way you don't have to restart the game from time to time again.
This can be done with a breakpoint. If you put a breakpoint inside the draw method, you're able to change the variables while the game is on break. If you disable the breakpoint and press continue again, then the game will continue with the newly inserted variables. This is what I've use as well for debugging/testing.

Though, it's also possible that you're basically asking how to use text/textbox input. In that case, I've found this answer from Stackoverflow, hopefully that'll be relevant to you.

---
Tags: c#, xna, game-design, sprites
---


title: Moving 3D object over Spherical terrain

text:
# Question
Title: Moving 3D object over Spherical terrain
I'm trying to control a 3D object (just a box for the moment) moving over a spherical 3D planet, I'm using a Ray to find the triangle in the sphere under the object. I'm calculating the surface normal and it's working this far but now I want the object to be rotated or just forced to be align according to the surface normal of the triangle from the sphere so that the object's down vector will be in the same angle as the surface normal vector so that it has the right angle against the surface.

I've searched the Internet but haven't succeeded yet after a couple of weeks. How on earth can I make my object align to the surface normal while moving freely around the planet/sphere?

I'm trying to make like a car driving around on the surface of a sphere.

The question is, how can I align the object to the surface normal? The code I have this far is to find the triangle under the box, now I would like to align the object to it.

I'm using Monogame in C# VS Studio 2017

# Answer
no time for a full answer, but assuming your pivot is centered, you can get the "down" vector (from the car POV) with `car.transform.position - sphere.transform.position` and then align the car relative to that vector, no need to cast a ray or calculate a surface normal (assuming you're sticking with a sphere). if you keep track of the previous position of the car on the sphere, you can calculate a directional vector from that position to the new position and then rotate the down vector 90 degrees along that movement vector. that new vector becomes the new forward vector of your car. alternatively, take the cross product of the calculated down vector and the car's right vector to get the new forward vector.

edit: this was meant as a comment, but was posted as an answer and I can't delete it using the mobile app. I'll fix it up to a proper answer tomorrow.
> 0 votes

---
Tags: 3d, monogame, sphere
---


# Question
Title: Valve Hammer Editor 3.4 won't load manually created map
I'm working with **Valve Hammer Editor 3.4** and trying to create a Counter-Strike 1.6 map with it. For this purpose, I've followed a YouTube tutorial.

I'm facing a problem where the editor won't run any map I created, it just says that map couldn't be loaded.

My log file is here: https://pastebin.com/QQHPXJGY

# Answer
> 1 votes
After couple days of looking for solution of problem i found the right one.All what you need to do is to download new compiler what is not going with valve,perhaps i use Batch Compiler.You can find on youtube or google how to set it up and you are ready to go.

---
Tags: hammer
---