#💻┃code-beginner
1 messages · Page 344 of 1
Tags are good if you're writing code quick and dirty while rapidly prototyping and don't want to write scalable code
Whatever a tag can do, a TryGetComponent<UniqueComponent>() can do the same
also the most important part, strings aren't type-safe, easy to mess up. spelling errors n all
tfw you don't receive an error for a misspelled tag . . . 😔
compiler: "its all valid!"
ive had that happen a few times lol. Also found out that I need shutoffs for in case the player becomes null
what is a shutoffs lol
null check . . .
ohhh
I have an inventory with itemslots and then items that go in that inventory
How would I save this to Cloud Save (json format)
Do I just put itemslot on each item, then if I get a new item I have to check all the items to see which itemslots are available
Or do I keep a separate json file that tracks which item ID is in which itemslot?
Or some other option?
save the item id and its quantity . . .
there's no quantity and the items are saved on Cloud Save in json, not in unity
json is json, doesn't matter where it saved
Presumably something like
{
"SlotNumber": 6,
"Item" : "Fork"
}```
the thing is, players can drag items, so slot 19 could be empty while 1-18 is filled and 20-50 is filled
if I just save them in one big json, then my server needs to check all those items to find an empty slot
Not sure why that's a problem or what it has to do with JSON tbh
Simply don't have an entry for empty slots
Json is just a serialized data format
You don't do code logic on JSON itself
but then I'd need a secondary json item like "inventory" that tracks the slots?
Why can't it just be part of the overall save file
I am facing huge performance dips in my game. Please help me find out why.
https://streamable.com/c3xii4
because there will be 100 items in that json file and I don't want to loop through all of them to find an empty slot?
Also you're talking about servers, and that's an incredibly vague term that means very little to us. Is this a networked game?
thats literally nothing
A loop over 100 items is nothing
nada, zip, zilch, none, nothing, not-a-problem . . .
so there's no need for a secondary file like inventory to track which slots are available?
remember this is on my server, not client
it might have to do it for hundreds of players at the same time
a very complex json can be literally a few megs or less, you shoud be fine
You have to realize we have no context about your game or your system
every time an item drops
Is someone trying to prematurely optimize
Someone do check this out
Why would JSON have anything to do with this. JSON is completely divorced from your runtime data structures
Do you get performance drops while building your game?
it's just the format I'm saving the items in
Don't mix up cold storage with runtime memory structures, they needn't be the same
didnt try that
If you have an item selected in Scene view while hitting play then the performance drops, in my experience, and I get at least 4x improved performance while just running in build mode
the serve rwould have to load the json from Cloud Save every time
then convert it to items, then loop through all the items
Why would it need to load json from cloud save every time
it's not a persistent server
What kind of game is this
Maybe explain context before the question
so if i build my game then I should see the actual performance right?
And the majority of performance bottlenecks, if real, come from expensive code put inside of Update() or FixedUpdate() loops
yes i have plenty
Yes, generally speaking, the built game is a realistic measure of performance
Show code you think is possibly problematic in Update or FixedUpdate
GetComponent should probably never be called in any Update cycle
I use Cloud Save daily and have thousands of reads and writes nary a problem
{
foreach (string tag in tags)
{
items.AddRange(FindObjectsOfType<GameObject>().Where(go => go.tag == tag).ToList());
}
if (pManager != null)
{
if(gameObject != null)
{
if (pManager.LaneSpeedIncrease == true)
{
Speed = 10f;
MoveCars(10f);
}
if ((pManager.LaneSpeedReset == true) || (!pManager.LaneSpeedReset && !pManager.LaneSpeedIncrease))
{
Speed = 5f;
MoveCars(5f);
}
else
{
Speed = 5f;
MoveCars(5f);
}
}
}
}```
bingo!
Yeah this is no bueno
whats wrong here
Update is run every single frame, so the faster you render, the more work you have to do
If you run 244 fps, then you have to do the loop 244 times, which, if it is enough work, will drop your frames
im guessing it needs fixedupdate?
Like an employee who finishes all their work and is given more work by their boss
so what do i change here
what else approach should i do
The logic itself needs to be restructured to only be called as-needed
Reduce duplicate logic. The precise approach depends and would need more analysis to figure out exactly what you're trying to accomplish
you're getting every GameObject in the scene, then searching for a specific tag, and converting that to a list, every frame. ouch!
For example, why do you set your cars' speed every single frame?
yeah thats what i was thinking might be wrong
The only thing that should be in Update, generally speaking, is inputs
Because players want responsive controls 100% of the time
But logic should be done at worst in FixedUpdate, and at best exactly when needed. Think of event-based systems, like if a car crashes into another car, then recalculate its speed
that is nothing . . .
But don't do math if nothing changed. Do math when needed.
so should i paste this code in fixedUpdate() or somewhere else where its actually more needed?
to reduce the frames it does calculate
i mean to ask in what situation shall i use fixed update
@slate haven also, this occurs within a loop which makes it worse . . .
yeah
yeah this also don't make sense if(gameObject != null)
if the script is running, aint no way the object script is on is ever null anyway
fix this part:
foreach (string tag in tags)
{
items.AddRange(FindObjectsOfType<GameObject>().Where(go => go.tag == tag).ToList());
}
where do i put this part
void Update()
{
// This is the most expensive part
foreach (string tag in tags)
{
items.AddRange(FindObjectsOfType<GameObject>().Where(go => go.tag == tag).ToList());
}
if (pManager != null && gameObject != null)
{
if (pManager.LaneSpeedIncrease == true)
{
Speed = 10f;
// This is likely going to cause unintended speed fluctuations since Update
// is based on render speed, not a fixed speed like FixedUpdate()
MoveCars(10f);
}
if ((pManager.LaneSpeedReset == true) ||
(!pManager.LaneSpeedReset && !pManager.LaneSpeedIncrease))
{
Speed = 5f;
MoveCars(5f);
}
else
{
Speed = 5f;
MoveCars(5f);
}
}
}
I refactored
okayy
The "which part" is "all of it"
Since Update is generally best-used for player inputs
You need to explain your logic before we can prescribe solutions
Personally, I would make each car move itself.
{
items.AddRange(FindObjectsOfType<GameObject>().Where(go => go.tag == tag).ToList());
}
Where do i actually put this part? Cuz I really need every item to be added in list every time an item comes
Cars are entities that can handle their own business
delete it
is there also more code than this? because this items collections would be increasing every single frame...
The code needs to be fundamentally restructured.
this has to be the largest list ever. every frame you are adding the same GameObjects that match the tags in your collection . . .
Cars should move themselves, so each car should have a script dictating its speed. If all AI cars have the same speed, then create a component AICarController and let it decide how fast to go.
what are you trying to accomplish with this piece of code?
- Avoid using tags if possible
- Do not put expensive logic in Update
- Only perform calculations when needed
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
My game has dynamic lanes, sometimes its 2 , 4 ,6. SO when a lane is removed (by player's actions), the laneless items appear to be on ground, I want to manage them
Like if i can remove them from the list, or make their speed such that they move out of the scene with the removed lane
public class NPCCar
{
public int Speed = 10;
private void FixedUpdate()
{
// Move down by {Speed} units every fixed interval of time
transform.Translate(Vector3.up * -1 * Speed);
}
}
What do you want to do with the GameObjects that are on the lane that is removed?
see, this is how I remove lanes, they go downward out of the scene. So if the items are already on the lane, they should go out with the lane's speed so it doesnt look absurd to the player. else if the item isnt on the lane, it shall get Deactivated/destroyed
Lane1
| - Car1
| - Car2
| - Car3
Lane2
| - Car1
| - Car2
| - Car3
Lane3
| - Car1
| - Car2
| - Car3
Lane4
| - Car1
| - Car2
| - Car3
Each car can be stored hierarchically under a "Lane" game object.
If the car collides with an out-of-bounds box, then destroy the car
The items should go out with the lane's speed?
Why are you measuring the speed of the lane and not just the speed that the player is going, which should be the same speed?
If player goes up 10 units/second, and the items are not moving, then the items should appear to move downward at 10 units/second while the player appears stationary
Exactly, so the player's actual speed is instead applied to other items
The player's speed is the source of speed for other items
So instead of associating items to lanes
Just let the items exist, and the player's speed can be used as the basis for calculating the speed of other items, whether they're on a lane or not
how?
i mean the player doesnt have any speed, we can either move it left or right thats it
public class StationaryItem
{
private PlayerCar _playerCar;
private void Awake()
{
// This assumes PlayerCar is attached to a GameObject called Playercar
_playerCar = GameObject.Find("PlayerCar").GetComponent<Playercar>();
}
private void FixedUpdate()
{
transform.translate(Vector2.down * _playerCar.Speed);
}
}
public class MovingItem
{
private float _speed;
private PlayerCar _playerCar;
private void Awake()
{
// This assumes PlayerCar is attached to a GameObject called Playercar
_playerCar = GameObject.Find("PlayerCar").GetComponent<Playercar>();
}
private void FixedUpdate()
{
transform.translate(Vector2.down * (_playerCar.Speed + _speed));
}
}
The player doesn't really have an actual speed, but it is the sole controller of the speed of every other object
so ur telling that i should associate speed of every item to the playercar.speed
whenever they are moving
Kind of
Every single object moves downward only because the player is "moving" upward
So at the start of their existence, they should locate the Player, determine how fast the player is moving, and then move downward every FixedUpdate
no no, they are actually going downward, out of the scene
Yes, the player is stationary and the items move downward
yes
Since all of the items move downward at the same speed, they must have one source of truth
The one source of truth is, in essence, how fast the player is (by illusion) moving upwards
Each individual object should handle its own speed
Or you can just add a component that makes each object fall
{
transform.position -= new Vector3(0, Speed * Time.deltaTime, 0);
if (transform.position.y <= -12)
{
if(gameObject != null)
{
items.Remove(gameObject);
op.DeactivateGameObject(gameObject.tag, gameObject);
}
}
}```
This is how every item (car, pickup, coins) are moving downward
They should not be controlled in an Update loop, but in a FixedUpdate loop with no logic beyond a simple transform.translate(go downwards)
that is convoluted
I don't like that function
{
if(pickup.LaneSpeedIncrease == true)
{
laneScrollSpeed = 5f;
laneMeshRenderer.material.mainTextureOffset +=
new Vector2(0, laneScrollSpeed * Time.deltaTime);
}
if((pickup.LaneSpeedReset == true) || (!pickup.LaneSpeedReset && !pickup.LaneSpeedIncrease))
{
laneScrollSpeed = 1f;
laneMeshRenderer.material.mainTextureOffset +=
new Vector2(0, laneScrollSpeed * Time.deltaTime);
}
```
This is how the lanes/ground scroll
It does too many things
aaaaaaaaa
too much logic
There should be one single Speedcontroller
it's fine to move the objects in Update, especially since they're manipulating the transform which doesn't use the physics engine . . .
Everything else that is meant to scroll down should observe the one source of truth and scroll down
Moving in Update doesn't make a lot of sense because you can just do it in FixedUpdate which is what physics handling is for
transform doesn't use physics but the point isn't just to not use physics, but to prevent unnecessary math
I suppose it works but it should be avoided by default
Movement logic goes into FixedUpdate and input logic goes into Update
I understand
This:
if((pickup.LaneSpeedReset == true) || (!pickup.LaneSpeedReset && !pickup.LaneSpeedIncrease))
Should be this:
/*nothing here*/
Laneless items still scroll down, yes?
Why a different speed?
different script for the lane, different script for item movement
cuz in lanes, mesh renderer is involved
Regardless of why, you can give them a separate component that makes them scroll down
items, just transform
Give lanes a ScrollLane component
Or have a LaneController component that handles how lanes scroll
And then give items an Item component with a MoveDown function, or perhaps a ScrollDown component that scrolls downward
Perhaps create a ScrollDownManager that manages all items as they scroll down
And each FixedUpdate, move the items down by some fixed speed
but isnt that same thing as having a script attached to the lane prefabs?
which handles its movement
Yes, if that's how it is now, then that works
As long as you extremely simplify that logic
It's like a car, right? You just hit the accelerator pedal, but the car just goes at its normal speed
If it's at 50 mph, it doesn't check to see how fast it's going
It just continues to go its speed
And if you want it to go faster, you change the speed
Lanes shouldn't check how fast to go in every frame; they should just go their assigned speed, and if a special event occurs, then the speed should be changed
so in a conclusion, I should have a single script which has the same speed for the lanes, and the items on it as well
1.) If the item is on the lane, no worry, they go out downward at the same time
2.) if not, just deactivate it
I do not quite understand what you mean by "they go out downward at the same time"
Lanes and items should go downward at the same speed, as far as I am understanding
I don't know why you would necessarily deactivate an item that's not on a lane, because how did it get there in the first place?
Also, I would destroy it instead of deactivate since I don't want to leave memory in the scene
cuz object poolin
That's a good optimization technique but I think you might have bigger fish to fry first
Up to you if you want to implement it
I think it might be premature optimization
Fully up to you
the items spawn from the very above in a random distance
thats why i told that some items might not be in the lane
- Each lane should decide to go downward at the same speed every FixedUpdate
- Items that meet criteria for being "invalid" can undergo your deinitizliation/deactivation procedures
Got it
And these should be kicked off by a particular event
They shouldn't check for the event
Like you don't check if someone's knocking at your door every second of your existence; you simply wait until you hear a knock
The lanes and items should continue to scroll until something tells it to do something else
Are you checking if it's on (a) lane, or (any) lane?
You can check for collisions
And collisions are okay to check for in FixedUpdate
Well, there's something called OnColliderEnter
bool isWithinBoundsRightLane = rightLaneCollider.bounds.Contains(go.transform.position);
if (isWithinBoundsLeftLane || isWithinBoundsRightLane)
{
}```
Which is a built-in function that triggers whenever something enters a collider.
this?
You also have OnCollisionExit: https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnCollisionExit.html
You seem to have implemented it manually
oh
I recommend using the built-in functions instead
okayy man
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour
{
void OnCollisionExit(Collision other)
{
print("No longer in contact with " + other.transform.name);
}
}
^ this is super neat
"Not in contact with lane anymore; uh oh, gotta deactive"
also where did u learn all of it?
By solving countless problems over and over and over
And getting things wrong over and over
Doing exactly what you are doing now for a few months
I also have a computer science background
I am midway in my career, but better late than never. You can learn anything given enough time
No problem!
why check if it's > 100 when you clamp it beforehand? also, by using Time.time, the longer the game is played, the faster Thirst will reach 100. basically, playing the game for longer than 10 seconds will instantly set Thirst to 100+ . . .
oh and don't cross post because i already answered you in another channel
i believe you want to add deltaTime here . . .
ok
when trying 2 create file at */myLogs/{DateTime.Now + ".txt"} i have UnauthorizedAccessException
what can i do for don't get it?
That would mean Unity doesn’t have permissions to write a file there
I believe logging to Application.persistentDataPath should work though
(And any subfolder of that)
Hi all, I'm playing with DOTS right now. I already have a spawner with it's authoring script and many inputs (number to spawn etc)
It works in the editor when i press play but after building the authoring is of course empty. How is it tipical to set default arguments for the authorings? Reading from a file, database? Setting an UI from scratch for each one of the authorings? is there any "ready to go" solution? It seems like a very common problem for everyone right?
ok, now directory isn't found
Application.persistentDataPath + @"\\myLogs\\"
\\myLogs\\ is not a valid path
use Path.Join and you might need to create the myLogs directory if it doesn't exist
i have this really disgusting code that doesnt quite work like i want it to. i have 4 tilemap presets and want them to procedurally generate as the player walks through the world in my top down 2d game. however i cant make it work so the map generates the right place. currently it just places them left, right, up or down from the starting position. i tried to fix this with the "PlayerY" and "PlayerX" variables but that did not work. the way ive done this might have been suboptimal, so if anyone has ideas on how to fix it, or rework it somewhat quickly/easily id love to hear it
https://pastebin.com/saDJHG4s
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Alright so to clarify my question from earlier:
My client is Unity, my server is non-persistent, a UGS C# Cloud Code Module saving data to UGS Cloud Save (json)
My Inventory has a limited amount of itemslots, that hold an item, it also remembers which item is in which itemslot
My server generates items and saves them to cloud save
What kind of structure should I use to properly save these items?
I'm thinking to save all of the items in a single json string/array, and then next to that, save a 2nd json string that remembers which item is in which itemslot. So that when I'm making a new item, the server does not have to loop through all existing items to find an open itemslot
Maybe you have to change a little your scope, more than just spawing a tile close to you I think is better if you check the direction where the player is going ans see if there is a tile on that direction. Other improve that you can use is to have a HasSet<Vector2Int> so you can check efficiently where are tiles generates and where not. Something like this, I haven't test it, is just to give you some idea of my approach: https://hatebin.com/zgspupkzce
Question dose any one know how to make water in unity?
Depends, if you mean just visually use shaders.
no like physics based water reactive
You will need some scripts to handle bouyancy.
Basically you want to add a force if an object is under a y level.
stupid question, but how do I access a variable from another script?
Class.variable
Make sure it is public.
thank you
OwO can u recommed me some like tuts or blogs that explain it in detail
Real world example:
MyPlayer.GetComponent<HealthScript>().Health = 0;
Sure, give a sec.
In this tutorial you'll learn how to set up boat movement and dynamic water physics in Unity.
Check out my devlogs: https://www.youtube.com/playlist?list=PLXkn83W0QkfmQI9lUzi--TxJaOFYIN7Q4
⎯⎯⎯⎯⎯⎯
Catlike Coding's article about shader-based vertex manipulation and Gerstner waves: https://catlikecoding.com/unity/tutorials/flow/waves/
Discord s...
Can i not use Monobehaviour classes, in a class that is dirived from the parent class? 😮
Got a abstract class, with a student thats linked with the Char class.
But my OnTriggerdEnter is not working. Its not detecting a touch.
public abstract class Character: MonoBehaviour
{
public class Student : Character
{
public void OnTriggerEnter2D(Collider2D collision)
{
Debug.Log("entering");
if (collision.gameObject.tag == "Player")
{
popupDialog.IsInRangeForDialog(true);
}
}
public void OnTriggerExit2D(Collider2D collision)
{
Debug.Log("leave");
if (collision.gameObject.tag == "Player")
{
popupDialog.IsInRangeForDialog(false);
}
}
yoo thanks
Keep in mind that this is a rather complicated topic and you might need to change some stuff and read up a bit more on it. The term you want is bouyancy force.
oooo i will keep that in mind
On the second Image you can see that you are using a BoxCollider, use a BoxCollider2D instead
oh thanks.. :{ oopsies...
don't worry, I know that because that happened to me too haha
what are hashsets? also i tried running your code and it spawns a prefab on the starting position, one above, one left, one down, and one right but when i move nothing new spawns. i dont really understand hashsets so im not sure what the problem is
equally stupid question, how do I call a function that was defined in a different script?
Via a reference to an instance of that script.
exactly the same way, but with the function name instead of the variable name
make sure the function is public
awesome, thank you
Set is a data structure where you can only have inside one of each value. For example Set<int> = {1,3,5,6}, if you try to add a 2 it will be added but if you try to add a 3 it won't. The hash part is the way the data are internally stored, that's the efficient way to make it access any value in O(1) (order 1, almost at the first try), so even if you have a lot of data inside that set you will always have it so fast, you don't have to check all content on a for loop, as you do with array and list. You can also use hash with other structures.
what is MyPlayer here?
the object that the first script is attached to? (the script trying to access the function)
because HealthScript is a component of MyPlayer
You can see more info here, on the microsoft documentation: https://learn.microsoft.com/en-us/dotnet/standard/collections/
so the component is the function and the first part is the object that the script is attached to?
the component is the 2nd script that has the function you want to access
it is the Game Object
.Health is the variable on the 2nd script that you want
please be careful of your terminology, object, Object and GameObject are very different things
confusing
only if you use the wrong one
or if you don't know the difference
I'm getting an error that says GameManager (the thing with the script I want to access) doesn't exist in the current context
int damage = Inventory.GetComponent<Weapon>().Damage;
All of them are objects. GameObject is also an Object too.
ok,
object is a C# object
Object is a Unity object
GameObject is a Unity object of type GameObject
show your code
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Does it exist in the context?
I'm guessing not lol
I don't have access to the Internet on my laptop, would it be okay to send pictures of the code? both scripts are only a few lines long
GameManager sounds more like a class than an instance of a class
then type them lol use ``
Is your GameManager class public or private/protected?
send the line where you have the error
GameManager.GetComponent<CollectableIncrementor>().Increment();
but without spelling errors
does your GameManager have a component named ColleactableIncrementor?
what Type is GameManager ?
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I don't have Internet access and it's hard to type out on mobile
I tried and it was just a big block
Well, we can't help you much if we don't have access to your error or code.
Maybe do something to have internet on the PC.
You have a phone don't you? You do know you can share your phone internet with your laptop
I fear my laptop will eat my remaining data in 2 seconds
If you want to be helped you will have to share relevant context
ahh i see. i think i have a general understanding of the code you sent, but if i want to add new ones as the player moves around, how would i do that? like add a new one in the way the player is moving
like i guess i would find they way the player is moving, look for the nearest empty space and if thats within a certain range, i would add a new tile there? but how would i code that
You will need and update with a method to create tiles around you. something like this: https://hatebin.com/ihtqleyhim
I'm just considering the four basic directions but maybe you want to check all around the player, even the diagonal, so you just have to add like new Vector2Int(1, 1) for Up-Right when you initialize your directions array
private void Update()
{
if(TimeInGame.TimeInGame_ >= 9)
{
Coffee_Function();
}
}
public void Coffee_Function()
{
agent.destination = CoffeeTable.position;
animator.Play("Walk");
if (agent.remainingDistance < 1)
{
animator.Play("Drinking");
}
}
its not going to the location
you're only showing an animation, you're not actually moving anything
agent.destination
it works when i type it in update
but not like that
can you help please
are you resetting the TimeInGame so Coffee_Function is only called once instead of every Update?
its called only once at 9
i don't know what resetting means here
im new to coding
right now the time is not resetting if that is what you mean
its basic
if it's working when you put it in the Update function, it's because it gets called several times
but if you change TimeInGame_ back to less than 9, your Coffee_Function will only get called once
but again, I don't see any code that moves anything
{
if (activeBattlers[i].gameObject.activeInHierarchy)
{
activeCount++;
}
} ```whats the best way to count this, currently its in update, but it just goes up and up each frame
count should only be 4 on start
activeBattlers.Count(x => x.gameObject.activeInHierarchy)
will you please make the effort to post !code correctly
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
As for improving "performance", there is no reason to make this more performant
Sorry i normally do
This is not the type of thing you should worry about
But if you are able to be imprecise occasionally, you can also consider only counting once every 10 frames for example
But again, not a lot of reason to improve performance this way, because the difference is negligible
i think i might just add it out of update, but at the same time thought there might be away without setting a bool
You can also make it a property
You can increase the counter when object becomes active and decrease when deactivated
Then just put this logic in there and count when the property is called
How would you determine if it gets activated/deactivated?
More boilerplate OnEnable/OnDisable which I think will just complicate something that won't become any better this way
Sure you could do on OnEnable/OnDisable or whatever sets the state of GO can manage counter as well
You would want to consolidate that kind of logic anyways
Yes, though you now delegate the logic to other things and you should probably introduce events to avoid coupling things together
So now it becomes worse again
Inject dependency 😄
if i have 1000 tiles of which 10 are alwaysFalse:
{
private int one = 1;
private bool alwaysFalse = false;
public TileOld(bool alwaysFalse = false)
{
this.alwaysFalse = alwaysFalse;
}
public bool Check(int two)
{
if (alwaysFalse) return false;
return one == two;
}
}```
that mean in 99% cases 'if' does useless work
so, if i do:
{
private int one = 1;
public func<int, bool> Check;
public Tile(bool alwaysFalse = false)
{
if (alwaysFalse) Check = returnFalse;
else Check = isEqual;
}
private bool isEqual(int two)
{
return one == two;
}
private bool returnFalse(int two)
{
return false;
}
}```
what are nuances here?
i read docs, but i'm not smart, it says it is slower and will generate garbage
This is likely perform worse since you can't get inlining 😄
It will allocate when Tile is created sure, but that's not the main concern
what is main concern?
i thought about inheriting and overriding it, but this looks prettier
Main concern is that Check will not be inlined by compiler
You are paying for function call, just to avoid conditional check
Function call is way expensive, to be clear
so, how to dodge the conditional check?
You don't
gamedev is full of frustration
I mean the performance we are talking here is negligible for 99% of time if not more
it's part of pathfinding, so i would squeeze maximum
High level concepts like delegate or virtual function are not going to help you here
Put the always false ones in a completely different collection to iterate over or remove those coordinates from the grid algo
This means more complications elsewhere no doubt
but i put them in same collection to skip other if checks
Programming is about tradeoffs
Did you actually run performance profile for this?
If not, do that first
Benchmark I mean
setting it up
The CPU is able to use branch prediction to optimize branches that are predictable.
so, the idea is basic branching is already good with all 'hidden' optimizations, i just need to reduce basic coding to less amount of basic coding, not to more of high-level stuff
ofc it all depends on my unique situation
why is this in the visual scripting namespace
Because you are calling wrong method?
The instance should be GO or Component not UnityEngine Object
it ended up being becuase there were some errors on the rest of the line
Sure
is system the standard library for csharp?
System is a namespace that some things in the standard library are inside
Hello ! I'm new to unity, I was wondering : what's the most comon / efficient way to store data for a game ? In my case, its just for saving scores and usernames (not even a password, its a simple project). I was thinking about json but I'm not sure if its the right thing to do
check out PlayerPrefs
https://docs.unity3d.com/ScriptReference/PlayerPrefs.html
thx
Whato do you mean by "store data for a game"? For what purpose? Do you mean save files?
I want to have a scoreboard that displays the top 10 players with their names and their score, but locally stored
Save it to a file
Isn't it better on PlayerPrefs ?
Check out my PlayerPrefsPlus asset. It is free
https://assetstore.unity.com/packages/tools/utilities/player-prefs-plus-124163
Be aware that PlayerPrefs are not Encrypted and can be edited by anyone
Not really. PlayerPrefs is the simplest, easiest to implement, and most straightforward solution. However, for any published games you should really not use it and instead use a text file. Writing data to a file is not hard and I would argue encrypting data is also fairly simple if you know what you are doing.
The issue with PlayerPrefs is that you save data as registry keys. The registry is really not used for that sort of thing and mainly saves system and application configuration data.
But if you really want to use Registry keys then you can just use the base system and save json under a string value.
I see, I think I'll go with the txt file solution then, thank you all for the ressources and the answers
It looks easier for me to implement it, already done that on a lot of c# project
What is best practice for creating popups using canvas's?
Got a friendly discussion on using a canvas as a prefab, vs keep it inside the hierarchy and set it as unactive/active...
I switched his code from doing setActive = false/true, to Instantiate(prefab gameobject).
public abstract class IPopup: MonoBehaviour
{
// Contains popup object
public GameObject popUp;
// Static variable to check if popup is already instantiated
private static GameObject instantiatedPopUp;
// These methods are virtual in case the implementation needs to differ.
public virtual void ShowPopup()
{
// Check if the popup has already been instantiated
if (instantiatedPopUp == null)
{
// Instantiate the popup if it hasn't been instantiated
instantiatedPopUp = Instantiate(popUp);
}
}
public virtual void HidePopup()
{
// Check if the popup has already been instantiated
if (instantiatedPopUp != null)
{
// Destroy the popup if it has been instantiated
Destroy(instantiatedPopUp);
instantiatedPopUp = null;
}
}
}
public abstract class IPopup: MonoBehaviour
{
// Contains popup object
public GameObject popUp;
// These methods are virtual in case the implementation needs to differ.
public virtual void ShowPopup()
{
popUp.SetActive(true);
}
public virtual void HidePopup()
{
// These methods are virtual in case the implementation needs to differ.
popUp.SetActive(false);
}
}
}
I thought Unity is all about prefabs and instantiating them when needed, and try to get as least as possible inside the hierarchy.
Its clearer due not having 5 canvas's stacked over eachoether.
But he mentioned its easier/less heavier if its allrdy there from the start of the game, and all u gotta do is set active/unactive
i personally use the SetActive(true/false) method to show Popups.
it avoids GC, which is better for performance.
You can reuse a single popup object if possible too
for me its easier to just disable or enable popups instead of Instantiate it every time and also destroy it every time.
UI elements with set active trigger redrawal of the whole UI if i remember correctly. Use alpha value on canvas component.
- Canvas doesn't have
alpha - That will block raycasts for the event system (which may or may not matter in your game)
Cant remember the component exactly. Set the block raycasts when changing alpha too. My ui performance was very bad on mobile before switching setactive to alpha
isn't that just a one time cost though?
But we plan to have 3/4 popups, and a startard UI. U all use 1 canvas's, and put everything inside there? O_o. Or have 4 canvases with each their use for SRP?
Compared with continuing to render the UI even when it's invisible?
It is a one time cost, but when you have a huge menu with a lot of different buttons/components, it actually is very heavy to redraw all that to enable or disable one component. I guess it depends on the individual situation
Its not for menu, its for an level where students have questions, which will generate a Popup where the player can pick/choose options based on the scenario. So its a dynamic popup with different options.
And i shouldnt see setactive like the same kidna thing if i alt-tab a game? its like running on the background, and that can be bad if u have like 4/5 popups on the background waiting to be activated over the level.
I have a pretty large menu. I deactivate everything except the currently visible screens.
I also lazily create things like settings screens
For a menu I would understand cuz its static.
It doesnt change over the map/ at different locations.
well, this menu is also used to display dynamic information
like when you configure an entity
lazy creation is very helpful there; I can avoid creating 20 different screens if I'm only going to click into one or two of them
I need a timer for my game. Is there a c# script somewhere I can copy?
google has thousands of examples
if you plan on doing development I suggest you get familiar with such a tool
"A timer" is really vague and a random off-the-shelf solution is unlikely to satisfy your particular needs.
for example here's a simple timer, but who knows if it's useful for you:
float timer = 0;
void Update() {
timer += Time.deltaTime;
}```
It's best if you give details about your specific requirements.
Why am I getting this error?
{
LookAtPlayer();
float distanceFromPlayer = Vector3.Distance(player.position, animator.transform.position);
if (distanceFromPlayer > stopAttackingDistance)
{
animator.SetBool("isAttacking", false);
}
}```
because ur missing the parameter
in animator
it has no idea what isAttacking is
Does your animator have a parameter named isAttacking
Ugh... The parameter in the Animator wasn't camel case. Thanks.
I found this one video but I got 2 issues. Let me go one at a time. I cannot see the text object in my game view
For My timer*
Sorry. I'm trying to add a simple timer for my game. I copied off a youtube video for the bulk of it but the timer isn't going down at all and instead only shows the initial string format from my code (I'll send a picture) any help is appreciated I've only been using unity for 3 months
again. Show relevant Code and Screenshots of scene/ text setup
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Then wouldn't it make more sense to ask your instructor who would be able to look at these screens and actually see what is in them
I'm seeing the timeless variable go down but the in-game text isn't changing
And the Instructor is just as inexperienced as I am
Then why are they instructing
The old teacher took a new job
2020s Instructors be like
He is actually a game art teacher
Barely passed the unity program cert as it is lol
anyway could you show what that error is btw ?

The null obj It's fairly irrelevant my game still runs fine.
Just the timer I'm trying to figure out. The text isn't updating
if it runs fine then why are you asking questions about how to fix a problem
Different red ! He was asking about ^^^
Trying to add the timer (screenshots above) timerLeft variable is going down but the text isn't updating with it
so does the text update at all ?
how are you checking the values going down for timeLeft
In the inspector
Hello, I have grid and the grid has a nested Tilemap object.
A script is attached to the Grid, how can I access the Tilemap from it?
does the text update at all ?
GetComponentInChildren<Tilemap>()
Also, if I want to get the position of a cell (e.g. to place a sprite on it), do I take the WorldToCell from the grid or the tilemap itself?
ideally make a filed in the inspector and link it there
Thanks Sir, will try now 🙂
When you say "nested" Tilemap object, do you mean a child object? The easiest way would be to just make a public variable and drag it in
That's of course the easiest solution, but the Tilemaps are generated dynamically and they are never the same.
cant you just store the Tilemap reference when you create/generate it ?
event could also work
public event Action<Tilemap> OnTilemapGenerated
...
OnTilemapGenerated?.Invoke(generatedTilemap)```
void SelectFirstItem()
{
if (!EventSystem.current.currentSelectedGameObject) {
var child = GetComponentInChildren<Selectable>();
if (child)
{
Debug.Log("SELECTING: " + child.name, gameObject);
child.Select();
Does this call OnSelected() on the child?
this doesnt seem to be getting called. SelectFirstItem is called onenable
does anyone know what the problem here is
youre doing it above rb, which hasnt been declared yet
yeah
didnt know ty
you shouldnt set it like that anyway, as that would only set it once and not get set again
You cannot use a variable in an initializer of another variable. Set it in a function
yeah
Nope just updates once to (0:00) : (1:00) and stays there
Sry for late response ^^^
can you post the code again with a code site from links
anyone know this?
I can try tomorrow class ended. Again no discord on school computers and the game is only stored on them
i found out i cant use Invoke and StartCoroutine in scriptable object, is there a way for me to time functions in scriptable object?
Stop watch
drive the timed part from a MonoBehaviour
idk if that can be done, i will explain.
basically im making an enemy ai system and each behavior (attack, chase, patrol, dodge) is each own SO class.
in the enemy script i have a logic system to determine how to use each SO.
so basically:
if (Condition for specific SO is met)
SO.DoAction();
and in the SO:
void DoAction()
// does the action
what i want is a melee attack that will, when called, wait a charge period, then attack, then wait a recovery period
It can be done. Basically keep a MonoBehaviour around to drive this system
it can be a singleton DDOL
the SOs can interact with the singleton to run coroutines etc.
You mean that it's destroying instantly and you dont want that to happen? It need to set up some coroutine to delay the clean up.
Set your particle effect to destroy itself upon completion
add a script to the explostion vfx that destroys itself after some time
does the OnSelect thing get called from this?
The Stop Action
https://docs.unity3d.com/ScriptReference/ParticleSystem.MainModule-stopAction.html
(its also in the inspector ofc)
how does that work with child systems
or I guess you would do a on hit -> particle system explosion
You need to call EventSystem.current.SetSelectedGameObject(..) to select it
EventSystem.current.SetSelectedGameObject(child.gameObject);
but I guess another issue is also if you were pooling the particle systems
oh okay, thanks
i think you gave me another idea.
the SO already has a reference to the monobehavior that is calling it, maybe i can just add a wait function to the monobehavior, and then after that function is over it will call another SO that will do the attack, and so forth and so forth...
basically in the monobehavior:
enum Action.....
void WaitTime(Action action, float timeUntilAction)
switch (action)
case ActionA:
Invoke("ActionA", timeUntilAction);
Sure but... just be aware that it matters which MonoBehaviour is running a coroutine
im gonna do that and tell you how it went but first i must tend to my hunger
the lifecycle of the coroutine is tied to that MonoBehaviour instance
im gonna use invoke not coroutine
it can often be helpful to have a dedicated MonoBehaviour instance for this
Invoke has the same limitations
strongly advise you stick with Coroutines
Invoke cannot be stopped individually, passed parameters etc
okie
well i plan for the enemies to be morons so i can just make sure that if they chose to wait for an action they are now committed to it and cant cancel an action, so just a bool to not allow them to call another action while they are waiting
it doesnt seem to be calling it after the changes shown in the image.
public override void OnSelect(BaseEventData eventData)
Is the code running? What's the log saying?
just call Emit on the ParticleSystem instance on the clone
sure or just make the prefab of type ParticleSystem in the first place
or have a proxy script on it that does the actual work of calling Emit
Ok?
yes that's what we're discussing
the code is running yes. but OnSelect isnt being called
get rid of child.Select()
well what parameter are you giving it?
How many times are you calling it?
what does your emission settings look like
still nothing.
for context im expecting this printed to the console.
im talking about the Particle system Emission settings
thats a line of code
10 rate over time might be why so many
what components are attached to that Standard GameObject?
Can you show the inspector
well how many appear now..
Text Button inherits Button
and which script is this code from?
This is from a script called select on enable, which selects first item on enable object
Ok well "SelectOnEnable" is not attached to this object
so that's why your code isn't running
did you try switching it to burst instead?
Its meant to be attached to root panels, which it is.
ok well OnSelect only matters for the thing that's actually being selected
yeah u dont need burst my bad, been a while since I've used ps
I know, the problem is that when the panel is enabled, the button text is not turning yellow
i thought that calling child.Select() would call OnSelect() on the child being selected
Only actually selecting it will do that
Yes because that actually selects them
is there anyway to manually call on select
yes EventSystem.current.SetSelectedGameObject(myObject);
from this screenshot it looks yellow to me
the border is yellow yes but the text isnt
the text is a different object
if you only want to manually emit particles, turn off all emission in the inspector
incl. setting rate over time to 0
this is my script https://pastebin.com/dz8f65vc
it instantiates random prefabs of tilemaps as the player moves around. however, after walking just a little bit around, unity chrashes. hypothetically it could be another script but im positive its this one. i believe its some optimisation issue, so if anyone likes optimisation problems id love some help on how to optimise this. the instantiated tilemaps also never get deleated no matter how far away the player is, which i probably also should add, but i dont think thats whats causing the crash
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
well yeah there's literally nothing in this script that tries to call Emit on the instantiated object
You saved the clone to a variable:
GameObject ExplosionClone = Instantiate(ExplosionEffect, transform.position, transform.rotation);```
But then you completely ignored it
same way you access other components
also if thats all that ExplosionClone does, can also just store it as ParticleSystem
If ExplosionEffect is of type ParticleSystem, then Instantiate will return a reference to the particle system
That is how you do it.
If it's not doing anything, then your particle system isn't completing. Make sure it's not looping for starters.
stop action was none ofcourse it didnt
why arent these showing up?
Because Button has a custom inspector defined
I think it's usually better to just make a separate component
rather than deriving from Button
and use an EventTrigger to hook up the events
or IPointerClickHandler/IPointerEnter/ExitHandler etc
but i need some things that only button has
is there no way to add stuff to the custom inspector?
anyone?
A crash usually means "infinite loop" so either a while that never exits, infinite recursion, or a Property that sets itself
Nothing in this code seems to be doing any of that
Put the box on an object that doesn't spin
And then making the spinning thing a child of that
then it would have to be my tilemap script. but thats just OnTriggerEnter2D - check if object has tag "SpawnPoints" if so disable it, and OnTriggerExit2D to enable it again. could that be the problem somehow?
So move the Hitbox object instead of Player
Show it
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I don't think this would go infinite. Pretty sure OnTrigger functions run on disabled objects specifically so you can do something like this. Still, you can eliminate this as a possibility by commenting out the OnTriggerExit function and seeing if it still crashes
no clue what happened but i commented it out, then it worked, then i undid the comment, and it still worked. thanks for the information on how crashes happen tho
do you think it would be necessarry to make the game delete tilemap prefabs that are far away, or will that not make any meaningful difference
how do i move an object relative to it's angle?
if i try to move it along the x axis, it doesn't move in the direction ITS x axis is pointing (red arrow on picture)
It does
transform.right is that red arrow. Use that as the direction
Are you moving the ship without moving the hitbox
Are you moving the Player object or the Hitbox object
Like what? Button is little more than a Selectable with IPointerClickHandler slapped on top. It really doesn't add anything special
wb the green one?
hello
how can i make the spriteRenderer of my object blink whenever his health is less then a certain value
So rotate the ship object but move the hitbox
by blink do you mean turning white or invisisble ?
you can play with the alpha value
(color would also be how you'd tint it white, or red, or black, or whatever you want to do)
invisible
the navigation thing
i sorted it out its fine
Navigation is all part of Selectable
and again you don't need your fields to be on the BUtton component itself, having a separate component would work fine, but glad it's working
I think I have both of these here, no?
public void TakeDamage (int damageAmount)
The problem is on the previous line. Probably a missing semicolon
{
public int HP = 100;
public GameObject;
public void TakeDamage (int damageAmount)
{
HP -= damageAmount;
if (HP <= 0)
{
PlayerDead();
}
}```
If I add one I get this instead.
public GameObject;
This is not a valid line of code
This variable is missing a name
you need:
<access modifier> <type> <name>
You have:
<access modifier> <type>
Oh yeah I meant to delete it, my bad, thanks.
Um... Looks like Unity is still in safe mode after relaunching the project even though there aren't any errors, how can I get it back into the regural mode?
doesn't look in safe mode to me
just looks like your console window is maximized
Press shift+space
Or double click on the title of the Console tab
Or right click it and press Maximize or Restore or whatever
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class Player : MonoBehaviour
{
public int HP = 100;
public void TakeDamage (int damageAmount)
{
HP -= damageAmount;
if (HP <= 0)
{
PlayerDead();
print ("is dead");
}
}
private void OnTriggerEntry(Collider other)
{
if(other.CompareTag("ZombieHand"))
{
TakeDamage(100);
}
}
private void PlayerDead()
{
GetComponent<MouseMovement>().enabled = false;
GetComponent<PlayerMovement>().enabled = false;
}
}```
So I'm not getting any errors but my HP is not decreasing nor am I losing the ability to move even if I lower it through the inspector.
The tags look right, the object that's tagged has a colider and so does the player.
the code in red doesn't stop the coroutine, why is that?
That's not how you stop a coroutine, in fact your code starts a new one and promptly stops it
StartCoroutine() returns a value, you need to store that in a variable and pass that variable to StopCoroutine()
ie.
Coroutine co = StartCoroutine(AnimationAAA());
// later...
StopCoroutine(co);
Your coroutine methods are also nested in another method, you might need to take them out if you get errors like "Coroutine xyz could not be started"
You misspelled OnTriggerEnter
Eh... Thanks, happens way too much, wish they supported VScodium and half of these issues could've been avoided. :'3
Use Visual Studio or Rider and you'll get autocomplete for those MonoBehaviour message methods
You can't get further help here unless you use a configured IDE
Yeah I probably should, just to not spam this channel so much, even though I don't plan on using unity much longer.
Hey so I have a "world border" that I want to follow the player as the player moves upwards., but I don't want it to follow it downwards
Is there a command that only adds the players positive y-axis movement to the object?
Check if the player is above the object. If it is, increase height to match.
This doesn't do anything if the player is below the object, so it won't move down
Yeah but the border is always gonna be below the player
It's a kind of trigger that "kills" the player if the players leaves the screen
I suppose I could link it to another object using that method
if playerYvelocity > 0.1 { move border }
And then how would I make the border move up?
Like what line of code does that
It's transform right?
google -> unity how to move object
Yeah but does that move it at the same speed as the player?
it moves it at the speed you tell it to move at..
Cuz the player is jumping so it's exponential
So instead of checking if the player is "above" the object, check if the player is some specific amount above that object. If they are, move it up until it's that distance away
If the player is closer than that amount, nothing changes
Yep, gonna have to google how to do that
I am confused with a how to convert rotation on the Z axis on float from (-1;1) based on the rotation on the Z axis. So I am making a steering wheel, when starting the game, the mappedValue should be 0, when the steering wheel is turned left by the maximumDegrees the mappedValue should be -1, and when turned right by the maximumDegrees, it should be 1 and smoothly interpolate, so when turned halfway it should be 0.5f etc... Althought this code doesn't work, and work differently under a child etc, what am I missing to make this work
public class SteeringWheelMapper : MonoBehaviour
{
public float mappedValue;
public Transform steeringWheelTransform;
public float maximumAngle = 90;
public void MapRotationToValue()
{
float rotationZ = steeringWheelTransform.localEulerAngles.z;
if (rotationZ > 180)
{
rotationZ -= 360;
}
mappedValue = rotationZ / maximumAngle;
}
private void Update()
{
MapRotationToValue();
}
}
Does anyone know or link to documentation that has code example of how composition works? All I found was explanation but no examples of how several scripts works together and how you use the same script for several object, like stat script for player and enemy
I mean that's basically it
What did I do wrong
Instead of having one script that's like "Player", you have a dozen scripts for things like "Damageable", "Controllable", etc.
Took a picture with your phone instead of a screenshot
https://screenshot.help/
Ik how to screenshot ðŸ˜
But fr tho what did I do incorrectly
really? then do it
- sent a photo instead of a screenshot
- didn't say what the problem is
Oh mb
I’m trying to get it to load the next level on collision of an object
Ah, so instead of incompetence it was active malice
Can someon help me? im making a 2d game for a college project, and i made a build of my game some time ago, and the scenes were changing as it should. But, when im playing the game in the "game" window of unity the scenes doesn't change, is it normal? Do i need to change some configuration?
(srry for the bad english, it is not my native language and im really tired lol)
Time to start debugging your code
I’m not gonna open discord on my computer and take a screenshot bruh. My computer is laggy
Then it's going to struggle running Unity, a significantly more heavyweight program
then don't expect to get help
Why do I need to screenshot in my computer?
you shouldn't been screenshotting !code anyway 👇
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
no, it's not normal.. something is broken. Debug your code and check your scene is setup correctly, etc
It's simple, when you ask here for help you abide by our rules, we do not conform to what you can be arsed to do
It could be an issue that you're reading the euler angles. It could occasionally use different euler angles which result in the same rotation as the one you expect. To solve this you would need to keep track of your own euler values
Although I dont really see either where you try to map it from -1 to 1. Diving by 90 would mean that at most the value is -90 or 90 but this clearly wouldnt always be true
Well sir, I didn’t know. Thank you for telling me
you make an excellent point. in that case here's the answer to your issue
Ok ok I see your point
I am making a VR game and a steering wheel to control the wheels. The vehicle controler previously accepted input (AD, -1;1) for the steering, and in my game you can physically grab the steering wheel and rotate it. I need to convert the Z axis rotation to a float (my new input)
and pass it to the vehicle controller to use that instead
So you can turn the steering wheel by 180 degrees left (-1 value) and 180 degress right (1 value). I need to calculate that value based on the rotation on the Z axis and I find it really confusing
what values does the steering wheel spit out when you turn it?
it depends, that what drives me crazy
what values are you asking about?
the mappedValue or localEulerAngles.z?
you can see the values in the inspector on the right
it works correctly when the steering wheel is not child of any transform
but when i put it under the car parent, the values are broken
relying on localEulerAngles read back from the Transform is a fools errand
you should maintain your own float variable for the rotation
that's what I thought but I am not sure how can i maintain my own float
sorry, was thinking it's a physical steering wheel
no sorry, my bad i phrased it wrongly
it's a steering wheel you can grab via VR controllers in game
and rotate it using your hands(Controllers)
all i want to do is to map the rotation on the Z axis to a float :/
Well ok actually if you want to read back the angle from the wheel itself you can use Vector3.SignedAngle(wheelHolder.up, steeringWheel.up, wheelHolder.forward) where wheelHolder is a Transform that is oriented such that it's at the "resting/neutral" position/rotation of the steering wheel if that makes sense
also a child of the car like the wheel itself is
yeah sorry
yeah
that gizmo is from Steering Pivot
yeah exactly and basically
and Steering Wheel at 0,0,0?
if you can imagine measuring the angle between the green arrow of this thing and the geen arrow of the wheel AROUND the blue arrow
that's what SignedAngle will do
alright let me try that
makes sense
public void MapRotationToValue()
{
float angle = Vector3.SignedAngle(wheelHolderTransform.up, transform.up, wheelHolderTransform.forward);
mappedValue = angle / maximumAngle;
}
private void Update()
{
MapRotationToValue();
}
so somethnig like that
where my maximumAngle is 180
well yea this works
now, how could i clamp the rotation kinda
clamping the mappedValue is easy enough
but how can i prevent the rotation (eulerAngles??) to go above my maximumAngle
if that makes sens?
like so you cannot turn the steering wheel anymore in that direction if it reached the maximumAngle, or mappedValue (-1, 1)
another thing I cannot understand that, somehows my rotation on X and Y axis still happens
when im holding the steering wheel
even when it's contrained in the inspector
these constraints prevent the physics engine from rotating on those axes
they don't prevent other things from rotating it
like the VR stuff
also why does the wheel need a Rigidbody anyway?
not with the asset im using
it's all physics based
the way it works is that
it snaps the hand to the steering wheel
using customizable joint
and that breaks the car stability aswell and a lot of stuff
and im trying for days now to make it work ;p
let me record a actuall VR gameplay to explain better what's happening
Hi can i have some help please. i dont under stand why my slider vlaue is -200. So currentEXP is 400 and expToNextLevel[CharacterStats.playerLevel] is 300. ```if (CharacterStats.currentEXP > GameManager.instance.expToNextLevel[CharacterStats.playerLevel])
{
CharacterStats.currentEXP -= GameManager.instance.expToNextLevel[CharacterStats.playerLevel];
var test = CharacterStats.currentEXP -= GameManager.instance.expToNextLevel[CharacterStats.playerLevel];
CharacterStats.playerLevel++;
expLevel.value = CharacterStats.currentEXP;
expLevel.maxValue = GameManager.instance.expToNextLevel[CharacterStats.playerLevel];
Debug.Log( test + "/" + expLevel.maxValue );
The line where you create your test variable has the -= too, which means it'll subtract twice
Assignments can be chained ie. var a = b = c; is perfectly valid
@wintry quarry if you are interested
basically the car is moving by physics obviously, to make it realistic
the steering wheel is a rigidbody, and the hand when grabbing the steering wheel makes a Joint between the hand and the steering wheel, and that messes the car physics and also the steering whel just.. umm isn't in the right place 😄
ah thanks sorry i thought that was just another short hand of take away
It is, a -= b is short for a = a - b
But you did var test = (a -= b) which does a = a - b and puts a into test
most likely b/c ur scales are off
they are at 1,1,1
they change in runtime to some weird values
not sure why, probably cuz of physics
and all the integrations and joints etc
ya, i just noticed they're pretty close to 1
wonder why they change from 1:1:1
thanks
the hand is creating with the steering wheel
ahh yea that could be it
lol
yea kinda 😄
besides the wheel going all crazy at the end.. it looks pretty good
yea it does but it's not useable haha
using localRotations?
to what?
im using a asset for VR Interactions
makes me think ur not using transform.localRotation for the wheels rotation
all the rotation is done by the hand
that is from external asset
all the grabing etc
yea, but it has to manipulate the steering wheels rotation
V3 has officially been released!
Auto Hand is a VR interaction system made in Unity, which you can use to make your own games
Find the asset here:
http://u3d.as/1NKZ
Join the Auto Hand community:
https://discord.gg/FrMhgEfGgE
it's based on physics
everything
that's why the steering wheel has to be a rigidbod
when i set the rigidbody to kinematic, it doesnt turn at all
but is still grabbable
true. but theres also local and world versions for Rigidbody functions
AddTorque.. vs AddLocalTorque
Relative Torque i mean
would need to browse the asset's code
but it might be even deeper
from Unity's code
in the XR Integration Toolkit
ya, but the asset may be assuming that all rigidbodies are global...
The joint should have settings to prevent this thing, even to solve the other issue about wanting to clamp it
that is the grabbable (steering wheel) component
if u have one nested as a child object.. the asset could not be able to account for that
ahh yea, since u have joints set up u should be able to constrain it that way
holy shit that's massive haha
that's the DefaultJoint
the hand+steering wheel connection uses
How are all of them locked but still moving? Maybe theres more magic going on
I'd expect angular Z to be not locked, whatever the other option was.
no clue
is this joint on the wheel? or is it on the hand?
checking rn
would take a minute because it's hard to debug stuff with your VR headset on 😄
i think we're assuming its on the wheel. thats y he said he expects teh Z to be unlocked..
it creates the joint on the hand
im thinking thats on the hand tho.. the joint its using to attach to items u grab
i grabbed the steering wheel with
ya,
Ah I see
ya, its def the code from the asset. not liking the way u have ur steering wheel/ heirarchy structure
What about the rb on the wheel? What constraints do you have
i can probalby change this in the asset's code, no?
can u show the hiearchy of this?
Yeah problem with Rigidbody constraints is they're based on world space
probably..
So if your car can turn that's not gonna work really
Yea that's unlucky
yap, im thinking the steering wheel is nested inside the car
so what about a workaround
that i unparent the steering wheel
and the player
and in the update i just move them to the proper spot
yea, let me try
let's see lol
That would be like making a physics scene wouldnt it?
should I also unparent the player from the car?
I would probably make a physics scene for inside the car 😊
because it creates a joint with the wheel
and when the player will be a child of the car
the car physics might be broken
ive done something similar.. where i kept the object a root object.. and then just used lateupdate to track it to the object it should be connected to
that way the rigidbody is still in world space..
or shoudl i just unparent the wheel lol
well how would that work in the long run?
i bet if u unparent it tho it will work as expected..
should atleast try it.. so you can confirm its the hiearchy
Steering wheel and player unparented from the car with a script that sets their position to a proper spot in late update
test number one 😄
test it... rotate it so its not facing forward anymore.. and then test again
can i also safely do transform.forward = transformToFollow.forward
for the player
so the camera works in realistic way
ya, that will sync their rotations
i have respect for u vr guys..
i couldn't develop with my head in a headset all day
heck yea.. howd u fix it?
nah its still broken
the steering is reversed
and there are very weird physics for the car
i was gonna say too.. if u unparented it from the car.. u could keep the rigidbody as a root object.. in world space.. and just use a hinge joint to connect it to the car
like collidrs under the car
but they arent there
look how the car is jumping with my head
this Harry Potters flying car?
Is there anything wrong with how I did this? The object I'm clicking was painted with the 2d tilemap gameobject brush if that matters at all.
It never prints the debug log
IIRC IPointerClickHandler requires a collider
do you have physics raycaster on the camera?
I have one that looks for something totally different
Oh are you saying just to use that instead?
just add that component
Docs say you need the physics raycaster and an event system
https://docs.unity3d.com/2018.3/Documentation/ScriptReference/EventSystems.IPointerClickHandler.html
Oh the component no I have a raycast that comes from the camera's script I'll try adding that
Ok it works thanks
ya, i would make the steering wheel a root object.. and just link it to the car via a hingejoint..
always check the docs 😉
waaaait
i think it works
and im just dumb
and made some modifications to the untiy's terrain yesterday
and they are invisible
yup xd
thanks for the help guys and @rocky canyon especially
Guys, why does my player fly away as soon as I add the character controller?
I'm using a rigidbody for the movement calcs, but I only want to use a character controller to check and manipulate the height of the player....
rigidbody and CC don't mix, choose one or the other
You cannot have both
I know, but idk how I would do my sneaking code otherwise 
public CharacterController PlayerHeight;
private void StartSneaking(InputAction.CallbackContext context)
{
Debug.Log("I'm sneaking");
if (isGrounded)
{
PlayerHeight.height = sneakHeight;
moveSpeed = sneakSpeed;
}
}
Nothing here indicates a need for a CharacterController
yeah the CC.height property just affects how tall the capsule collider is. either just swap colliders on the rigidbody or make its collider shorter
naming your CharacterController variable PlayerHeight is also really confusing
Ait I'll try that
Why does this code only return 1 item in the loot table even if there are 2?
Because you return possibleLoot on the first iteration of the loop
this really shouldn't be a loop
You should just do Item item = lootTable[0] and then run your code
hello guys, does any one know what the code is for dynamically adding a TextMeshProUGUI to a UI Panel via script?
Instantiate a prefab as a child of the panel, or create an empty object then use AddComponent
Got it. Thanks
AddComponent is a static function of GameObject that takes a generic akin to how GetComponent works, yes?
It is not static, it is called on an instance of GameObject
oh I see it. Thanks
wait, what exactly do you mean by that? how would that look like?
Here's my current code
List<Item> GetDroppedLoot()
{
int randomNumber = Random.Range(1, 101);
List<Item> possibleLoot = new List<Item>();
foreach (Item item in lootTable)
{
if (randomNumber <= item.dropChance)
{
possibleLoot.Add(item);
print(item);
}
}
return possibleLoot;
}
This code is different
i just fixed it :)
The code you showed returns the first thing it finds in the list
but you mentioned an optimization i don't know how to code
this is how the code is meant to work
OH
nvm
No, I didn't. Your loop was literally doing nothing before so it was pointless to use one
This one actually does use more than the first element so a loop makes sense
{
_recoilPhase = RecoilPhase.Kick; //Go To Recoil Positiion
_currentRecoil = _recoilStrength;
yield return new WaitForSeconds(_recoilDuration);
_recoilPhase = RecoilPhase.Recovery; //Reset To Original Position
_currentRecoil = -_recoilStrength;
yield return new WaitForSeconds(_recoilDuration);
_currentRecoil = 0;
}```
I'm trying to create some code for a recoil function but it doesn't seem like it's going back to the original position. I don't want to hardset it using Vector3s, is there a way to somehow get it to return to it's original position? It's basically pulling the camera up for a duration then pulling it back down
Hi, how can I stop the cards from occupying the same place?
anyone knows why the wait function isnt... well waiting? i can shoot infinitely fast
(this is 2d btw)
Where do you start this coroutine
Also you're missing a yield return
wait so i need to put it in a function of IEnumanator for it to work?
Yes that's how WaitForSeconds works
it delays a coroutine
it doesn't do anything anywhere else
ahhhh alright thanks
hi yall:
for some reason, in editor play mode(and in a test build i just made), when i look at a particularly performance heavy section of the game, it causes my mouse sensitivity to increase by like a lot. im assuming it has something to do with the code, and that its handled in update and based on framerate of the game or something. how can i fix that in code? i want the game to be able to run on any framerate. i use cinemachine for the camera handling and this bit of code is the only other thing that uses the camera
alright i did this but i cant shoot at all, sorry for the ping but can you please help me again?
Where do you call StartCoroutine
i havent... where should i call it?
OH MY GOD I AM SUCH AN IDIOT I FIXED IT THANK YOU!
my character in my game has inventory slots, in a small window of rotating items ^^. each itemslot is represented in the heirarchy as an object with an itemslot monobehaviour script on, which holds serializable properties. the itemslots are held in an array in the inventorymanager. I'm trying to implement code to make the slots "shuffle" up or down when you press left/right with the inventory open, but I can't seem to crack the final implementation of making the slots actually move their values, any advice?
debug seems to show everything working as intended, but no values actually move
there's no need to actually move the objects around in the array
also your code is only doing that - moving items around in the array
it isn't going to move the position of the objects in the game
Why does my activeBuildingType doesn't change when i click the button???
add a debug.log and make sure it runs
!code\
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
test
@deft grail sorry where should i add it, after activeBuildingType = buildingTypeSO; ????