#archived-code-general
1 messages ยท Page 49 of 1
Vector3.Dot
returns 1 if they point in exactly the same direction, -1 if they point in completely opposite directions
So basically how similar they are on a scale of -1..1?
how can i reset material values when theyve been altered in code?
Materials are usually persistent data. If you're altering them at runtime you're probably making a new instance of them, so what you will probably want to do is either cache the original values or find a way to create another instance.
If I have a velocity of Vector3(1,1,1) and I want to change the velocity on the Z to 0.3 I can just set vel.z = 0.3. But what if I want it to be 0.3 on an arbitrary axis normal like (0.5, 0.5, 0)?
You can set whatever velocity vector you want
Alright does anybody have any idea why my instanced GameObjects are destroying themselves after exactly 1.6 seconds
Without seeing the script thats doing it? No.
Ctrl-F "destroy" in your project in VS
I use it 3 times and twice is in my singletons
I don't want to set it directly, I want to scale it along a normal.
i seem to have screwed up my damn ui materials
its because i was changing offset of stuff, how can i fix this
git revert
Ultimately you need to set it if you want any of your changes to apply, since vectors are value types.
but then i lose all my other files progress
Discard changes to those files
how can i do that in rider?
Yes, but I also need to do the math first, which is what I'm not sure of.
I dont use rider, but I imagine it could have git integration. Otherwise just use a git client.
You take whatever direction you desire and multiply by length.
Set it directly... to that normal, scaled however you wish
how do i disable visual scripting?
Uninstall the package
I wasn't explaining it well but I got it sorted out to do what I want.
Did someone had problems updating Burst compiler from 1.8.2 to 1.8.3?
I updated correctly, but a workmate pulled the commit and he got an error when importing the package. He tried uninstalling the package, reboot Unity (which automatically installed 1.8.2) and then updated to 1.8.3 but got an updating error...
We are using 2022.2.5f1.
So I'm using blender, and I got this error using a qc file
don't crosspost, you already were told where to ask
this is Unity dc, and coding channel
I have a script with a public list attached to a game object but the public list isn't showing up in the inspector. am I missing something?
then maybe the list type isn't serializable in the inspector
if it's custom class or struct you need the System.Serializable for it
ohoho you're a genius
I bet that's it
absolutely was, thank you!
ack what a dummy. I did this to debug my inventory system. I wrote the complex part where if you get something it tries to merge stacks with what's there. forgot to do the other part where if there's no stacks, it just makes a new stack 9_9
in Unity is there such a thing as a "frill blocker" - aka some way to suppress a terrain's detail layers in a space on a temporary basis? or do I really have to edit the detail map each time?
So my player has many scripts attached to it, many of these Scripts reference each other, but because Networking is hard and it messed up my head, I ended up using 2 types of referencing throughout my project.
The first way is the common one which is to just [SerializeField] the class that i need, Like "" Oh i need to verify if the player is grounded here on the gun script"", So i just serialize and set it in the inspector
The other way is to have a Player class that holds all the scripts in the player and if i need something i just do ""Player.Movement.."" etc
Does using the second way for all my references affect performance?
do i need to cache it on start or is just asking the Player for the script fine every frame?
Uhh that was long, if anyone can answer i'd be thankful
I think "performance" is the wrong question here and most likely irrelevant
the bigger question is do you really want to tie all the references to your Player object
that kind of hard couples everything to this Player script
hmm, you have a point
imma try and clean things up and leave the player class just for spawning and saving the current server players
If I made a Serialized Field called Sounds. Its a list of sounds in my Audio Manager's inspector. How do I get the first int in the list to change its Audio Clip.
Just the first bit of the code. I'm basically trying to do this.
the first sound in the list = this.musicObject.GetComponent<AudioSource>();
Theres a GameObject I have attached to the Audio Manager that I want the first in the list to be equal to
Looks like this
would it be like... sounds[0] =
or something
Show your existing code first
but likely... sounds[0].clip = something;
kk
OwO
Lemme try that and then send my code if it doesnt work. (Also thank you)
[System.Serializable]
public class Sound
{
public string name;
public AudioClip clip;
[Range(0f,1f)]
public float volume = 0.7f;
[Range(0.5f,1.5f)]
public float pitch = 1f;
[Range(0f,0.5f)]
public float randomVolume = 0.1f;
[Range(0f,0.5f)]
public float randomPitch = 0.1f;
public bool loop = false;
private AudioSource source;
public void SetSource (AudioSource _source)
{
source = _source;
source.clip = clip;
source.loop = loop;
}
public void Play ()
{
source.volume = volume * (1 + Random.Range(-randomVolume / 2f, randomVolume / 2f)); ;
source.pitch = pitch * (1 + Random.Range(-randomPitch / 2f, randomPitch / 2f)); ;
source.Play();
}
public void PlayWalk()
{
source.volume = volume * (1 + Random.Range(-randomVolume / 2f, randomVolume / 2f)); ;
source.pitch = pitch * (1 + Random.Range(-randomPitch / 2f, randomPitch / 2f)); ;
if (!source.isPlaying)
{
if (source.isPlaying == false)
{
source.Play();
}
}
}
public void Stop()
{
source.Stop();
}
}
{
public GameObject musicObject;
public static AudioManager instance;
[SerializeField]
Sound[] sounds;
private void Awake()
{
if(instance != null)
{
if(instance != this)
{
Destroy(this.gameObject);
}
}
else
{
instance = this;
DontDestroyOnLoad(this);
}
}
private void Start()
{
for( int i = 0; i < sounds.Length; i++)
{
GameObject _go = new GameObject("Sound_" + i + "_" + sounds[i].name);
_go.transform.SetParent(this.transform);
sounds[i].SetSource (_go.AddComponent<AudioSource>());
}
PlaySound("Music");
}
public void PlaySound(string _name)
{
for (int i = 0; i < sounds.Length; i++)
{
if(sounds[i].name == _name)
{
sounds[i].Play();
return;
}
}
//no sound with _name
Debug.LogWarning("AudioManager: Sounds not found in list, " + _name);
}
public void PlayWalkSound(string _name)
{
for (int i = 0; i < sounds.Length; i++)
{
if (sounds[i].name == _name)
{
sounds[i].PlayWalk();
return;
}
}
//no sound with _name
Debug.LogWarning("AudioManager: Sounds not found in list, " + _name);
}
public void StopSound(string _name)
{
for (int i = 0; i < sounds.Length; i++)
{
if (sounds[i].name == _name)
{
sounds[i].Stop();
return;
}
}
//no sound with _name
Debug.LogWarning("AudioManager: Sounds not found in list, " + _name);
}
public void SwitchMusic(int sounds)
{
sounds[0].clip = this.musicObject.GetComponent<AudioSource>();
}
}
Sorry its a big code
Idk if theres a way to shrink it in discord or not ๐
yep - sounds[0].clip = whatever;
you're supposed to share large code snippets as links to paste sites
!code
๐ Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Ok thank you
sounds[0].clip = this.musicObject.GetComponent<AudioSource>();
I tried that
It comes up with an error under the sounds part of the code
it's an audio clip
not an AudioSource
you can't put an AudioSource in an AudioClip variable
what are you actually trying to do
I think you have this backwards
I think you want to set the clip of the audio source to the clip from your sounds array
I'm trying to make it so that when I switch scenes, the music in the AudioSource will change to be the music indicated in the object "Music" in the scene
what's the point of the array and the sounds object then
I'm 90% sure you actually want something like this:
public void SwitchMusic(int index)
{
AudioSource source = musicObject.GetComponent<AudioSource>(); // why isn't this just a direct AudioSource reference????
source.clip = sounds[index].clip;
}```
My Audio Source holds and controls all audio in my game. Jumping Landing attacking etc...
So I want my music audio to change when I switch only to a specific scene.
Idk maybe that'll work ๐
Yep seems like this is what you want
Also your code is kinda insane
seems like you have 2-3 duplicate methods that do the same thing
Hi! Long story short, I want to have a list of terrain objects that spawn their own named empty object to be used as a parent. The tool updates automatically whenever a new element is added or taken away, but the implementation is quite messy.
My question is: If I were to remove an element of the list within the Inspector, is there any way to, through code, find out exactly what object was removed without the manual, keeping copies of the list and checking for differences?
ChatGPT just generated a solution to a problem I was stuck on for hours lol
And the code was simpler and cleaner than anything I could find online
I just got here, any way tou could brief me on the problem it solved?
Ok so I did the thing. It definitely is doing something and plays the music, but now it doesnt play the music continually when I switch scenes which was the purpose of making the Music section of the audio manager.
I think maybe if I call upon a script in the musicObject it might work, but I'm not sure.
BUT You definitely fixed my problem with finding out how to get that code to run.
So thank you. It helped me.
I was trying to make an object run away from the player. I tried extensive geometry based solutions to no avail. ChatGPT solved it in under 10 lines of code.
It's one vector subtraction to get a direction facing away from an object ๐ค
Yeah well your mom.
The question is - did you actually learn anything?
Yes I did lol
If you did then good
True, and I made some NavMeshAgent mini tools for things like that XD
I was using A* Pathfinding but I'm not sure if I'm going to keep using it. There are simpler solutions
Sorry for @ing you again ๐ฎ
Lemme know if I shouldnt do that.
I also tried changing index to 0
how do i change a variable's name ? Also, if i change the name of a variable, does it affect the value of that variable in the inspector?
i want to change the name of a variable everywhere in code
How do I set the speed of AddForce()?
The "speed of add force"?๐ค
Yes ๐
That question doesn't make any sense.
It makes perfect sense
Right now when the player jumps, they jump way to fast, I want to slow it down
It doesn't.
AddForce() is a method. It doesn't have a speed property that you can set.
What should I use then?
You misunderstood my reply. I was talking about how your question does t make sense.
You can still use AddForce for jumping.
How can I slow it down?
Just reduce the force that you pass into it.
Wouldn't that make the player not jump so high then?
It depends on how you apply the force. If you apply it regular force over time, as long as it's higher than gravity, it will move the object up.
Basically each frame you'd be applying an acceleration equal to jump force - gravity force.
If you're using an impulse mod, that's a different story though
So I should use the Force Mode?
Again, depends on what kind of implementation you want.๐คทโโ๏ธ
I just want the player to jump lol
If you want more control over it you could even set the velocity manually
How might that be done?
Just set the velocity of the rb.
You should know how to do that if you're asking in this channel.
If not, ask in #๐ปโcode-beginner
Setting the velocity gives the same result as AddForce unless I am doing something wrong
how would I change the fog settings from code? I want to use the default built-in fog I think in the lighting menu. I want to change the color and thickness, but I haven't found any way to do that. Anyone know how?
Just reduce the numbers.๐คทโโ๏ธ
rb.velocity = new Vector2(rb.position.x, jumpForce);```
What am I missing?
On that line nothing.
Well what other line would there be?
I don't know. I don't have your script...๐
Reducing jumForce should reduce the velocity.
This is just teleporting the player up to the jumpForce
That would just make the player not jump so high then though
Teleporting..?๐ค
Then the way you process jumping is wrong for your use case.
You told me to do this 
I only told you that you can have more control over it if you set velocity.
But I need control on the speed lol
There are a lot of other factors that could affect the whole jumping mechanic.
And you do have. With velocity.
It sets the "speed" directly
Welp, not much I can help you with without seeing your code.
Also at this point, move to #๐ปโcode-beginner
rb.velocity = new Vector2(rb.position.x, jumpForce);
The movement speed does not affect the jump
75 is still a lot
I need it to jump that high
It means 75 units/s. Which is more than 1 unit per frame.
It needs to be able to jump over the blocks
As you can see, 75 barely gets over the block
I see that it's really weird, but not much I can do without seeing your code.
This is my only code for jumping other than checking if the player can jump
What makes you think that other code doesn't affect it..?
There's clearly something resetting the velocity of the character.
Because it doesn't
No its not?
Well, that's just how it looks like on the video. I can't say for sure because I don't see your code.
Anyways, if you know better, then why even ask here?
isGrounded = Physics2D.OverlapCircle(groundCheck.transform.position, 0.2f, collidableLayer);
if (Keyboard.current.wKey.wasPressedThisFrame || Keyboard.current.spaceKey.wasPressedThisFrame) shouldJump = true;
if (shouldJump)
{
shouldJump = false;
if (isGrounded) rb.velocity = new Vector2(rb.position.x, jumpForce);
}```
That part is fine.
That is my code
I bet there's more code than that.
Not trying to be rude, but you shouldn't be trying to help people here if you don't know much about coding.
That's funny, but ok.
If you don't want to cooperate, then good luck solving the issue on your own.
Anyone who knows code should know that there isn't much required for a simple jump and all I'm not showing you is the global variable declaration and functions
You literally have not given me a solution lmao
What about the other script?
What other script?
Because I don't have your code lol
I gave you my code from the beginning
Or where do you have your movement code?
You don't need my entire class, you just need my jump code
The same class as jump
Then share it...
^^^^ This is my jump code
Ok, good luck then...
Thank you.
If you change your mind and decide you need help after all, feel free to share the whole script.
You're funny ๐
@pearl otter If you're not going to share your code in entirety for review, then please refrain from posting questions.
Also as mentioned above, you'll need to modify velocity each frame, and manually reduce it by some deceleration factor until it reaches 0, if you want to fine tune how much and fast you jump.
I shared everything related to my issue. I don't see other people sending their entire class to get help with one line
Or you take a short cut and use something premade:
https://www.youtube.com/watch?v=3sWTzMsmdx8
Yeah, I am trying that now.
When someone asks for more, you give more. If you're going to argue what you think people need to help you, then don't ask questions. We get this from time to time and it's a waste of everyone's time.
Please go through our conversation, I provided all of the jump code, and he did not give me any solution other than "use volocity", "reduce velocity", etc. There was no reason to give more code
I did go through it. ๐
Is that the code you are using? Why would you use rb.position in the velocity?
Its just absoultely wrong and doesnt make sense. I didnt even notice it at first
They seem to know better than us Osmal. It's useless to argue with them.๐ฌ
Lmao
I just grabbed some movement code from online but I got it working now
Hi, I have a UI button that increases the number on a UI Text every time it is pressed, however I would like to carry out this increase whilst the button is held down rather than pressed once. Any help would be appreciated
You could do this with the Update event or a Coroutine
I'm not entirely sure how you check if the button is held down though
Would need a custom button component or use an EventTrigger component to catch the OnPointerDown/Up events.
With a custom button you can implement the IPointerDown/UpHandler interfaces.
So I'm using a coroutine to make my character jump
the coroutine checks if the player can jump for a few frames after they press the input
that way it feels more responsive
but
if the player spams the jump button
the player jumps super high
im assuming its because there are multiple coroutines running at once
Just to confirm, you are checking if the player is on the ground right?
Try moving that code to the end of the coroutine when the jump code runs
Cache the new coroutine and check if it exists before starting a new one. Reset the reference when done jumping.
Or you could actually use a variable
i stopped all corotuines the line before i start a new one
i figured that would do the same thing
but the problem persists
let me screenshbot my code
Then there can't be 2 coroutines running at the same time. Share your code.
i am doing the groundcheck in the coroutine
!code
๐ Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
That's not gonna stop the coroutine:
StopCoroutine(RememberJump())
i tried multiple ways
No it won't but if I am reading your code correctly, the player shouldn't be jumping in mid air
Cache the reference when you start the coroutine as I suggested.
how would i do that?
sorry if that is a bit vague
i don't think i really understand how caching works
the main problem is
Check the stop coroutine docs page. They have an example
not that the player jumps in midair
ok i will get back to you once i try
but if a spam right before the player toches the ground he launches way up
I would just create a variable "isJumping" or something, then when the player clicks the jump button, it sets the variable to true, then after the coroutine ends, set it to false. Then when the jump button is clicked, only start the coroutine if isJumping is false
that may work
@cosmic rain would i find the cacheing stuff here? https://docs.unity3d.com/Manual/Coroutines.html
In this case, caching is simply saving something as a class field so that you can access it later.
You want to cache the Coroutine instance that you start.
ok
this worked ๐
nevermind :(
it seems to reduce the frequency of it happening
but it still happens
Hmm
In StartJumpSequence(), can you use a Debug, we will be able to see if the function is being called multiple times
ok
so jumpstartsequence dosent seem to be getting callled multiple times
and checkingJump seems to be true
when the glitch bounce happens
which is also wierd
but
the jump method is getting called 2 or 3 times when the glitch bounce happens
Ah
I'm not sure what your for loop is doing, but it looks like its running multiple times before the player jumps and/or the ground check is above the radius to the ground when loop repeats
what i was trying to do was
when the player pressed jump
the coroutine starts
it checks if the player can jump once every frame for a few frames
if at any time the player can jump the coroutine stops
and the player jumps
Oh like inverse coyote time
the for loop just lets me control how many frames i can check for
You press a bit early, and you want it to wait for landing and exectuing the jump then?
is that not what the for loop is doing?
yes
that's the goal
I'm not really understanding but It seems like Osmal does so hopefully they can help you out
alr
Also just a tip, if you are planning on making your variables changeable in the Inspector, you should make the variables private and use [SerializeField] unless you need to set the variable from another class
I would start a coroutine when I jump but I'm not grounded/allowed to jump. I would also stop all existing coroutines when doing this.
You should use myCoroutine = StartCoroutine(...) to cache/store the current coroutine when starting, andStopCoroutine(myCoroutine) to stop any ongoing coroutines when it starts, like dlich was hinting
i wanted to use serializefield but i got a bunch of these errors
ok im gonna try
can't you use checkingJump as a condition when starting the coroutine, not start another if that is true
Hmm, strange
i have it so that if checking jump is false start another corotuine
k
because checking jump shows if there is already another coroutine
i think
but im gonna try cahcing the coroutine instead
what do i call the mycoroutine
That's not gonna fix it. It has the same effect as what you're doing with checkingJump.
As has been pointed, your add force probably getting called several times, while the ground is within the grounded check radius.
that does make sense
IEnumerator
right ok
You are storing the function, not coroutine
You should be able to identify wether you've already applied the jumping force and if you have, don't jump.
Coroutine
No. They need to store the Coroutine instance that StartCoroutine returns.
Ah I see
wouldn't StopCoroutine(myCoroutine) stop the coroutine i am caching?
Umm yes
but don't we want to stop all the other coroutines?
I also didn't read your code or the discussion in great detail, just saying how it can be done
do you think i could just not apply jump if the yvelocity is positive?
You would need a list then but from your debug test, only one coroutine is being started
myCoroutine would be the old coroutine in this case
Stop that, then start another one and cache it in
But if this isn't what the others are telling you, ignore me
ok
That's one option, yeah. Although if you for some reason can have positive y velocity when not jumping, then you wouldn't be able to jump.
For example if you're moving up the slope.
It would be best to just set some flag when you actually started jumping and reset it when you're grounded.
ok
how do i get the width and height of text?
im working on a tooltip that needs its background to fit the text within it
background is an image
ok i got it
but i think the way im checking if the player is finished jumping is a little clunky and/or not performant
right now, im checking if isJumping is true and the y velocity is less than 0 and the player is grounded
is there a simpler way?
You just need to set isJumping to false at the start of the frame if you're grounded.
the problem is the player is grounded for a split second after isjumping is set to true (and the player jumps)
becuase my overlapspehere that checks for if its grounded is a little big
So what? Your coroutine should be running by then.
You just need to avoid starting the coroutine if you're already jumping.
Aah.
im gonna try putting the jumping end check at the last line of fixed update
or maybe even lateupdate
so it happnes after the player is no longer "grounded"
maybe
nevermind
I think you should just rework your ground check.
It's not ideal when it reports wrong results.
alright
im trying to make a ui text object folllow the mouse using:
transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition);
but its in the bottom left corner all the time
it moves slightly when i move the mouse but why is it not moving right at the mouse position?
If it's a UI text, it probably uses RectTransform and is in screen space
Could try to modify the recttransform's anchoredPosition instead
ah okay
anyone got workin with epic sdk? platformInterface.Initialize doesnt work, throws null exception?
{
ProductName = m_ProductName,
ProductVersion = m_ProductVersion
};
var initializeResult = PlatformInterface.Initialize(initializeOptions); <------------
if (initializeResult != Result.Success)``` crashes at initialize
y cant i drag "Text" into the "Result" field in the player script?
You have to pass references to in-scene objects to prefabs via code (or assign them as overrides when they are already present in the scene)
https://unity.huh.how/programming/variables/other-members/prefabs-referencing-components
oh, did not know that
@frosty scroll
isSameInteracted = (interactibleInstanceId != interactible.GetInstanceId();
CheckInteraction```
Instead of switch
Never used it myself
not quite sure what you mean by stable... they're not persistent id so it would be changed on restart etc...
Regarding your question the answer is, it doesn't matter, you're good!๐
Just store the object references?
Whenever I uncomment this function, it gives 24 errors, all relating to not closing off a parenthesis or something and end-of-file stuff, but I checked it and it doesn't seem to have that sort of problem. Maybe there's a problem with using tuple arrays or params with tuples?
I mean a better solution would be to not compare instance ids but compare instances instead
no
If there's any difference, it's so small that you can't even measure it. But comparing references is really fast, the reference is just an integer internally
on the other hand comparing strings isn't (relatively) fast at all
how to place some objects (meshes) in front of UI, and some behind UI ?
i can either get them all in front or all behind
not both in same time
(don't remember if ids are strings or ints)
and you're doing extra method calls to retrieve the id in the first place
void somefunc<T>(params (bool b, T gen) paramfoo){}
for some reason this isn't possible, isn't there any workaround for this?
I could just use a struct perhaps, but any other ideas?
proly you just want this public static void Test<T>((bool b, T t) test){}
wait but doesn't that only allow one argument?
yeah, it doesn't let me do this:
I was thinking of using structs, but I also wanted to have the cleanliness of tuple params as shown in somefoo()
you mean like this? void Test<T>(params (bool b, T t)[] ppr){}
yeah, but it calls an error unfortunately
wdym?
aight goodluck
I used return as a variable name
Why does adding colliders inside colliders cause Physics.SyncColliderTransform take far longer?
I have made the colliders have different layers and in the Layer Collision Matrix the layers are set so that they don't collide with each other.
Active Constraints jumps from 382 to 147.97k with no reason
hello, where do i post ad related queries?
whats the best way to do a grid?
like some objects take up multiple tiles and I dont want other objects to intersect them
Anyone have a better name for this test?
well you can utitilize tilemaps if it's a 2d game (they do work in 3d too), there's a Unity Grid component, but im currently writing my own Grid system that utitilizes that component to give me more robust controls
does default unity grid support things that occupy multiple tiles
no but you can either
- write a system that stores tile occupation yourself and check against that
- use a tilemap and check if the tile at the corresponding index is of a certain type
the 2nd way you can just draw on your tilemap to store things like 'cant place stuff here'
how would checking if a certain shape can fit work on a custom grid system
im assuming it would use a 2d array
so the way i'd handle it is every object has a 'center'
then for each object I would store the offsets for each tile it occupies
those offsets would obviously change for each possible rotation of your object
then you check for the center, and for all of the offsets, if a tile is already occupied
you could also just set transforms and raycast to the floor and then turn that worldpoint into a grid coordinate I guess?
Question: When using the Profiler TimeLine... is possible to highlight (or somehow make easier to find) method made by me? I mean, methods in my namespaces or maybe methods in the Assembly-CSharp assembly, or methods in an specific type?
Because there are so many stuff there that makes difficult to find my code
Hey guys, I was wondering if anyone could help with the structuring of game logic?
Currently I have something like this, which uses a lot of callbacks but it feels messy
and it's going to get longer with more and more nested timers
I'm thinking of trying to make states but I'm finding it a little confusing
Do I make states as a class for which I then pass in lambdas in the constructor for what the switching conditions are, or do I make it an abstract class or an interface and make a new class every time I want to define a new state?
Do I have to check the conditions every tick, or can I run states on a more event based system?
If I do make it an interface, how would I then define a bunch of states and chain them together, as lots of information needs to be shared between them
sorry what are you trying to do exactly? its a bit confusing to me
So I'm trying to make a digitalised version of a board game, and I'm trying to write the logic for it
I'm unsure of how to structure it however
I think I'm entering what is called 'callback hell'
in the game there's a president and a chancellor, and different states. President picks a chancellor, people then vote on the decision, then different things happen depending on what the result of the vote is etc
currently I have these nested timers
so in that screenshot I sent, I create a timer which lasts 30s and the president is asked to select a chancellor. If the timer runs out before the president selects a chancellor, a random president is picked. If the president does make a choice, the timer is stopped early. The next state of the game is nested inside that timer, where a new timer is then created and the process basically repeats
It feels like I'm doing things wrong
But I'm struggling to think of how to do it with more well defined states
right
if I had an interface where would I actually define the classes
so would I make a new script for each state?
hello,
Just a simple question : I try to switch to the Unity Localization package
BUT, I already have and interface that used in all my app
string Localize(string key)
As GetLocalizedString in the package seems to works only on Async way, I have a problem
Is there any equivalent function without async mode ?
Do you think of some workaround that prevents me to rewrite all my scripts that need localization ?
you can call an async method from a non-async context, it will just run synchronously if you do
but I will block the app some frame no ?
yes, but so will any non-async options
something as GetLocalizedString(x,y).Result ?
or maybe more GetLocalizedString(x,y).GetAwaiter().GetResult() ?
idk the equivalent for AsyncOperationHandle ๐
How to init BoxCollider with Bounds? You can't set it directly, and basic "center" and "size" is not enough when object is scaled or rotated.
Screen 1: White - bounds, green - box collider.
Screen 2 and 3: Object "bounds" is the same in both cases.
If u want to rotate a gizmo
U need to set the Gizmos.matrix
So u can do
Gizmos.matrix = transform.localToWorldMatrix;
U should call change the values of the Matrix before u draw with gizmos
And make sure this is also within OnDrawGizmos() or OnDrawGizmosSelected()
Gizmos is the correct one here, they are drawing my bounds as the should. I want my collider to be the same as the bounds.
Ur colliders are same as ur bounds
The gizmos are not rotating so as i said u can use Gizmos.matrix to do it as well
@small trench Damn, you was right. But I still want the effect that I have with first gizmos on my screenshot. No easy way to rurn of matrix on the collider? XD
everything is gone
Hey, i'm wanting to make currency in my game slightly less susceptible to simple cheat engine edits, curious how people might handle this?
This data is stored in a save file thats obfuscated a bit, relatively small, i don't care about perfect security just want to deter simple edits.
The only time I am currently reading from the file is when you load into a game from the menu and it stores that data in a temp PlayerData class.
Right now when you try to buy from a merchant it uses the value from that PlayerData class, so technically you could modify that at runtime.
Would it be more ideal if I get the true value from the save file each time you purchase something?
I'm mostly concerned about accidental read/write issues
Alright, so I'm using UI Builder with a ListView and this is my code:
Debug.Log("First SOURCECOUNT: " + keyListSearchParameter.Count);
if (CompareList(keyListSearchParameter, (List<String>)keyList.itemsSource))
return;
keyList.itemsSource = keyListSearchParameter;
baseBindItem = (e, i) =>
{
Debug.Log("SECOND SOURCECOUNT: " + keyListSearchParameter.Count);
(e as Label).text = keyListSearchParameter[i];
};
keyList.bindItem = baseBindItem;
keyList.itemsSource = keyListSearchParameter;
keyList.Rebuild();
keyList.RefreshItems();
UpdateTranslationCounter();
Can someone explain to my WHY the Debug.Log() lines create DIFFERENT output?!??!?!
Coroutine...how do I wait for 1 frame?
yield return Wait(1);
would this do it?
(solutions I found online are outdated as I can't do this anymore
yield return WaitFor.Frames(5); // wait for 5 frames
yield return null
thx
BackgroundButton.clicked += () => buttonClicked();
buttonClicked is a Coroutine...is this how I would do it or do I need to do the
StartCoroutine(buttonClicked()); somehow?
Technically yield return anything where anything is anything that isn't a YieldInstruction will wait one frame. null is typically used.
thanks ๐
Yes, you need to start the coroutine normally even if it's in response to a button click
gotcha, it wasn't throwing errors so wasn't sure
MonoScriptImporterInspector.OnEnable must call base.OnEnable to avoid unexpected behaviour.
UnityEditor.Tilemaps.GridPaintPaletteClipboard:OnDisable () (at Library/PackageCache/com.unity.2d.tilemap@1.0.0/Editor/GridPaintPaletteClipboard.cs:347)
this error at all worrysome?
is it possible to recalculate the price every time you access it, like from a GetPrice() function or property? so if the price is based on how much you have bought/sold in the past, then you just have to store that quantity and recalculate the price using that, and a player would have a hard time figuring out they can change that number which might break other things
Technically yes, all the purchased items are technically permanent unlocks and i record your owned items in one place
Reading from a file every time is a performance nightmare and also does nothing to prevent cheating. The user can simply modify the save file
you know what i think i misunderstood what you were saying, i was imagining a market where the price changes based on player supply/demand or something i have no idea why
Thats true, i mentioned i dont care about perfect security.
The save file is obfuscated to prevent simple text edits, it should also be relatively small for the scope of things
but similar idea maybe just adding some obfuscating calculations so the player can't find where the currency is
like some ratio or constant that always gets applied to the stored value
I just want to deter simple text edits and simple cheat engine edits on your money value
I use this one
except my savesystem is trash
if you want to deter simple cheat engine edits you can't have a single int money field anywhere in your code
you'd have to obfuscate it in memory the way you do in the save file
And then use a property getter/setter to appropriately read/write the value as needed
Yeah im only using that value to display things on screen
So if you changed it it wouldnt matter, as long as you get the true value from the save itself right?
(when doing transactions)
so you would only store a value called A, and have a property of GetPrice function that returns A * obfuscating Ratio, and whenever you store the value you store A / obfuscatingRatio, A would have a name that they cant figure out what it's for
as a very simple example
I wouldn't use a ratio, rather something like a bit rotation cipher or something
I tried using multiple save system before, but that just backfired on me because i used playerprefs, but you can do better
Yeah i've learned a bit about encryption/obfuscation in some security classes
note none of this is going to prevent modification/cheating, it will just make it not work properly
the money amount will still change
Yeah if you mess things up it currently just slaps you with a fresh save file lol
it just won't change to the number they want
Okay, just trying to prevent average person from doing an easy edit.
Thats one thing that bugged me in risk of rain 2 is how easilly you can give yourself infinite currency or unlock challenges that are otherwise very challenging
This is true, theres no competitive edge in this game either.
You just have the fancy hat sooner than others
Why spend money on a game and then ruin the experience for yourself?
I have come to the conclusion that unity is bad and it should burn 
Thats sort of my teams mentality yeah
I hope all players have this mindset
GTA San Andreas came with the cheats built-in and it just improved the experience ๐
OHDUDE
GTA is a lot more sandboxy though, but yes lol
theres also caves of qud, that have debug in setting, they deliberately give the option to cheat, makes me feel not wanting to
private float originalSprayInterval;
private int originalSprayAmount;
private float originalSprayBulletSpeed;
private int originalBulletAmount;
private float originalBulletSpeed;
private float originalBulletInterval;
private int originalBulletDamage;
private float originalTimeBetweenActions;
private float originalSpawnInterval;
private float originalSpawnAmount;
private float originalShootAmount;
private void SetOriginals()
{
originalBulletAmount = shootAmount;
originalBulletDamage = bulletDamage;
originalBulletInterval = bulletInterval;
originalBulletSpeed = bulletSpeed;
originalShootAmount = shootAmount;
originalSpawnAmount = spawnAmount;
originalSpawnInterval = spawnInterval;
originalSprayAmount = sprayAmount;
originalSprayBulletSpeed = sprayBulletSpeed;
originalSprayInterval = sprayInterval;
originalTimeBetweenActions = timeBetweenActions;
}
IEnumerator UpdateAttributes()
{
scale = (float)atm.health / (float)atm.maxHealth;
// Limit so that game doesn't become unplayable at very low health
if (0.3f >= scale)
scale = 0.3f;
shootAmount = Mathf.RoundToInt(originalBulletAmount / scale);
bulletDamage = Mathf.RoundToInt(originalBulletDamage / scale);
bulletInterval = originalBulletInterval * scale;
bulletSpeed = originalBulletSpeed / scale;
shootAmount = Mathf.RoundToInt(originalShootAmount / scale);
spawnAmount = Mathf.RoundToInt(originalSpawnAmount / scale);
spawnInterval = originalSpawnInterval * scale;
sprayAmount = Mathf.RoundToInt(originalSprayAmount / scale);
sprayBulletSpeed = originalSprayBulletSpeed / scale;
sprayInterval = originalSprayInterval * scale;
timeBetweenActions = originalTimeBetweenActions * scale;
yield return new WaitForSeconds(0.2f);
}
Is there an easier way to do the above? I'm trying to make a boss fight where the different variables scale depending on the boss's health
I don't know why but it just completely removes the last entry in my keyListSearchParameter List. I have tried everything, I am going insane..
This is long af so I don't want to keep doing this same thing over and over again if possible
!code
๐ Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Thought it wasn't too large because it didn't hit the Discord's text limit but ok
almost every line of this snippet is flawed
what is your goal? what are you trying to do?
with a little thought you could reduce that to 3 lines of code
Well yeah but I thought it would have been easier for them to understand with that long block instead of with my bad explanation skills
I made a search function for a ListView that contains strings as its elements
What am I doing wrong?
could be like a free singleplayer game with transactions to speed up progress
what's the game / what's this part of the application? like big picture
Any game with microtransactions would store inventories in a cloud database
Recommendations for a cloud database to use? I havent looked into that quite yet
I know how to jsom save/load but thats about it for saving stuff ๐
Just know there were an insane amount of options to try and pick from
Is there a way to disable Importing Assets programatically? I have a large function that writes thousands of files but it keps hung and interrupted by an import
how challenging is it to port an already existing point and click game to mobile (assuming the game is not too intense)?
i appreciate this is pretty dependant on how intense the game is - and i don't have anything to show - I'm just curious on whether or not it's an acceptable workflow to start a project targeting one platform, and (should the need arise) port to mobile down the line
It's an editor window that helps with localization and translation
hmm
have you looked at the Unity Localization package?
how challenging is it to port an already existing point and click game to mobile (assuming the game is not too intense)?
if you used Event System (void OnPointerClick(PointerEventData pde)) and URP, it should Just Work
no way
that is music to my ears
you will have a working, fairly playable game.
if you use Canvas to lay out your game, you will want to explore the different scaling settings.
Yeah, I wanted to make something on my own as a learning experience
if you are using sprites, there are lots of good camera layout tools. cinemachine's are very good. even if your game is laid out with sprites
i see. unfortunately i have not use UIToolkit enough to help out, i'm sorry
does this extend to other parts of Event System also? i.e. OnDrag
no problem!
yes
if you used Event System, everything will just work
to be honest, that's how a lot of my point & click games end up looking. almost everything ends up on the canvas
if you use Input. somewhere, especially Input.mousePosition, you will want to change that. the best thing to do is to avoid Input. entirely. you can retrieve pointer data from the input modules. using Input System can also help, because ExtendedPointerEventData is more useful
yeah I don't plan on going back to the old input system
then your thing is going to work very well
you can use the device simulator in the editor to test the different layouts easily
another valuable package is Notch Solution, which will give you UGUI components that help you lay out in response to the presence/absence of notches and rounded corners
i personally prefer to use physical canvas scaling and an aspect ratio fitter instead of the other scaling options, so that i can have better control over what should be website-style layout versus game content that is generally designed for a fixed aspect ratio*
but it may be redundant for your game
by "physical canvas scaling", are you referring to unity's built in canvas scaler?
yes
awesome. ty for the help & linking me to Notch Solution!
how would i save game data like xp and levels and stuff? would i use player prefs for that or save it in a json or something?
create your own save data class(es) and save to json or binary . . .
playerprefs should only be used for options or settings . . .
would you recommend json or binary? im watching a brackeys tutorial and hes showing me how to do it with binary, but apparently json is viable too and its easily viewable and stuff
json is fine . . .
you'll find a plethora of tutorials online . . .
awesome, thank you
What's a good approach using interfaces on components? Considering that you may want to create dependencies in inspector and so on?
https://pastebin.com/p29ts8Bf Is there some better way than doing something like this?
class Switchable : MonoBehaviour {
virtual void SwitchOn() {}
virtual void SwitchOff() {}
}
// already exists. does not need to be modified
// door does NOT INHERIT switchable
class Door : MonoBehaviour {
void Open() { ... }
void Close() { ... }
}
// references door.
class DoorSwitchable : Switchable {
[SerializeField] private Door door;
override void SwitchOn() { door.Open(); }
override void SwitchOff() { door.Close(); }
}
class DefaultBehaviourSwitchable : Switchable {
[SerializeField] private Behaviour target;
override void SwitchOn() { target.enabled = true; }
override void SwitchOff() { target.enabled = false; }
}
class DefaultGameObjectSwitchable : Switchable {
[SerializeField] private GameObject target;
override void SwitchOn() { target.SetActive(true); }
override void SwitchOff() { target.SetActive(false); }
}
class Switch : MonoBehaviour {
public Switchable[] switchableObjects;
...
}
no need for interfaces
don't use them here
you might need some default behaviour for switchables
you'll be able to do it this way
Lets say hypothetically you wanted to implement more interfaces so you cannot go with inheritance?
there's no inheritance here
door does not inherit switchable
DoorSwitchable has a reference to a Door
@hollow stone do you see?
if you have more "interfaces" do the same pattern
My brain is computing, one sec^^
it works in the inspector
you wanna add behaviors to doors? add behaviors to doors.
how would i check if guns are unlocked on a save file? i was just thinking that i could give each gun an ID from 0 to 6 for example, and then say like true, true, false, false etc
would this be a valid way to do it?
start with a unity tutorial about saving #๐ปโcode-beginner
im doing that now
finish the video first ๐
I see. It was just an example, but I realized it's solvable by other means.
do you see what the pattern is here?
if you want to add an aspect to a pre-existing component, write a new component and reference the existing one in it
99% of the time interfaces are misused by unity developers
Aha ๐ Figures.
not because they don't make sense, but because in unity development you have full access to the source code, and you can modify nearly anything, so they are a worse option compared to alternatives
Lets say you have an input reader class instead, that you want to be able to mock. E.g.
public interface IInputReader {
public UnityEvent<Vector2> MousePressedEvent { get; }
}
public class GameInputReader : MonoBehaviour, IInputReader {
...
}
public class BoardStateMachine : MonoBehaviour {
private IInputReader inputReader;
...
}
in my experience, when you have access to the source code, they are useful for things like
interface IReadOnlyValues {
int value { get; }
}
class Something : IReadOnlyValues {
[SerializeField] private int m_Value;
override int value => m_Value;
...
internal void SetValue(int inValue) => this.m_Value = inValue;
}
public void RenderValue(IReadOnlyValues hasValue) {
// guaranteed to not modify the value of what was passed to it
this.m_TextField.text = $"{hasValue.value} points";
}
Love the instant thumbs down x)
this is oneo f the worst ways to use interfaces lol
How come?
class InputReader : MonoBehaviour {
public UnityEvent<Vector2> mousePressedEvent { virtual get; }
}
class Vector2UnityEvent : UnityEvent<Vector2> {}
class DefaultInputReader : InputReader {
[SerializeField] private Vector2UnityEvent m_MousePressedEvent;
public override UnityEvent<Vector2> mousePressedEvent => m_MousePressedEvent
}
public class BoardStateMachine : MonoBehaviour {
[SerializeField] private InputReader m_InputReader;
}
@hollow stone now this can be edited in the inspector easily
i will also caution that this doesn't make sense. if you want to have au nified view of input, use input system
i don't think you're going to have more than one kind of input reader are you
you might even have only 2
you have full access to the source
based on how you are authoring this right now @hollow stone , you're going to be leaking details about reading input to the so called board state machine anyway
like a vector2 is not enough information
so
i don't know. give me a real example and i can show you
Yeah, this is what I'm considering to just go for instead, but I'm curious what happens when you need to follow two abstractions then.
what do you mean?
The DefaultInputReader is implemented using the Input System to trigger the event. But my naming is probably bad.
How would yall do drop chance for items?
Just straight rand math seems hard if you want like 0.015% or other insanely low chance
Can you explain what you mean here? Do you mean how I get the interface?
Right now my ugly way of doing it is like this;
public class BoardStateMachine : StateMachineBase {
[SerializeField] private GameObject inputReaderObject;
private IInputReader inputReader;
private void OnValidate() {
if (inputReaderObject != null && !inputReaderObject.TryGetComponent<IInputReader>(out _)) {
inputReaderObject = null;
}
}
private void Awake() {
inputReader = inputReaderObject.GetComponent<IInputReader>();
}
...
}```
Lets say I would've implemented ICharacterInput and ICameraInput on on the same DefaultInputReader to be used in different aspects of the game.
How can i change this script so the gameobject doesnt spawn every frame
I'm trying to set a boolean once a shake finishes with DOTween. The event never occurs though; isShake continues to be True.
transform.DOShakeScale(duration, strength).OnComplete(() => isShake = false);
does anyone know why the above code would not set isShake to false upon completion?\
i have a problem with these rotation camera scripts, it doesn't activate both script to make camera a rotation, but only one work. But how can i activate both script at same time?
Wasnt sure which channel to put this in but does anyone know why setting the collider type seems to do nothing to my tiles? :
it does activate both if theyre both enabled. if you want any help, share the code first
probably a mistake in the scripts
sometimes your tilemap will not update rightaway. reloading the scene or playing then stopping should rebuild your tilemap
When or how often do you want it to spawn?
do the debugs work?
yes
Both are overwriting the value of rotation.
yeah well I think the rotations are just overriding each other
@formal bolt Got it to work, had to fully restart the editor very strange
but how.do i fix that?
You need to evaluate using a single instance of current rotation.
!code
wish I had coded this better early on ๐ญ
๐ Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Cache an instance of itemsList and you'd have shorter lines? ๐ค
only once when health reaches 0
true thanks, hadn't thought of that lol
It should work unless you're not resetting health - not visible in the image. Also perhaps consider instantiating on health loss rather than polling each frame.
Example: cs private float health; public float Health { get => health; set { health -= value; if(health <= 0) Instantiate(...); } } @ember cedar
Where the above would have your health member as private and instead provide a property to modify/read health.
Properties are simply methods under the hood but uses the same conventional format as the actual variable - note that value types are not accessed by reference but by value (similar to position, rotation and whatnot from the property members of the Unity Transform component).
You'd simply do cs player.Health -= damage;//Propertyrather than cs player.health -= damage;//fieldproperty being denoted with PascalCasing rather than camelCasing as it's simply a method under the hood - original Unity properties use camelCase but these were done so during the early years of Unity and would cause a lot of havoc if suddenly changed (or maybe they've got other reasons).
I have a question I'm not sure how to describe exactly, so I'm not sure what I would google.
I have an Xml file of cards (and card attributes). It is a list variable accessible from "deckXmlFile.mainDeck.Cards"
<cards>
<card id="1" name="Test Name" pairName="Test Name Back"/>
<card id="2" name="Second Card" pairName="Second Card Back"/>
<card id="3" name="3rd test card" pairName="3rd test card back"/>
</cards>
If you only had one of the id numbers, for example id = "2". What's the best way find this line, or find the other attributes, such as the name?
I know I could make a method that ran a for loop, testing for the id. But is there a built in ability to do this? Something like
string card = deckXmlFile.mainDeck.Cards(id="2")
Depends how you're parsing the XML
If I was planning on accessing these by id a lot I would probably put them in a Dictionary after parsing the XML with the ID as the key
Hey does anyone know why is this line highlighted?
I have the netcode package installed
whats it say when you hover over it
namespace netcode doesnt exist in the namespace unity
Nevermind I closed and reopened the project and it works fine
Hey, how can I decrease the scale of a cube when I click on the corresponding side? (x side -> x-scale -=1)
You might have to regenerate project files
how do i make it so the audio sources pause what theyre meant to play instead of stopping it fully?
use the normal of a raycast to determine which axis to scale on
currently theres a weird thing where if i pause while a clip is playing, the next clip that plays, both clips overlap each other
when I access a transform via script (for example I print the name of its GameObject) it instead acts like its one of its children. I dont know why. It happens with a transform in the skeleton of my game character and just on some of them. Is this a bug?
anyone got an idea if this is a common mistake
SOunds like a bug in your code or your understanding of the hierarchy
You'd have to explain exactly what you mean
it instead acts like its one of its children.
what does this mean exactly?
I access a transform in my hierarchy and I simply print out its name and it returns the name of one of its children.
if I print another transform it works as intended
Prove it
How are you "accessing" it exactly?
I saved the the transform in one of the components
show the the hierarchy, show the code, show the inspector, show the console, etc
its hard to prove
Ok so what is GameManager
what is TPS
what is Torso
how are all these things assigned
it sounds like you've simply assigned something incorrectly
also when you print you should add some kind of label to it:
print($"Name of the torso is {GameManager.TPS.Torso.name}");```
Otherwise you may also be mixing up the log with a different one
This should be easy to prove, simply show all those fields, how they are assigned, etc.
alright I will keep digging and come back with better prepatation if I dont find the mistake
found my mistake... forgive me for wasting your time. Wont happen again
Yo, idk where to ask this but I'm making a 2D game and for some reason my player won't collide with the wall and will just go straight through it.
The wall is on UI layer, and the player is on Player layer, both have 2D colliders, non-trigger, player has a rigidbody and moves using MovePosition. In Physics2D settings the collision for UI/Player layers is checked.
What could be the problem here?
nwm, I had a kinematic rigidbody
how can i change sound effects based off what floor im on? so like wooden floors would make wood sound, stone would make stone etc. how can i make different tiles have different values?
Making a system and besides the numeris other better solutions I can't use because of unities super outdated C#, now this one has no work around as C# 11 has abstract static methods which is the only way for me to do what I want to do...
I very much doubt that a C# 11 feature is the only way to do what you want to do
Scriptable Objects / tile , store their sound there then retrieve it with a GetTile method
I very much doubt you have the knowledge to make such a claim
scriptable object per tile?
can i have like an array of tiles that would all make the same sound?
so like a wood scriptable object orr something
Per tile type
When you move you can check the tile youโre on with GetTile method
can u give me the documentation for this pls
I don't want to use reflection and bad coding practices so no there isn't another way.
Nobody said anything about reflection
But you haven't described your issue at all
So impossible to give you any advice
Yeah and I am not gonna I don't need help
Then why did you post here lol
Your reply was just rude so I was being snarky
thanks :)
so like GetTIle(player.transform.position)?
To vent mainly, this is code general.
wasn't really a rude reply tbh, im also interested to see what it is you absolutely cannot implement without abstract static
but you got pretty defensive immediately & if you don't actually need/want help then hey ho
GL
Your opinion, and thank you for your wish of luck
what counts as code beginner and code general?
I assume it doesn't matter much but regardless
i would just post in #๐ปโcode-beginner, until you're comfortable enough that what you're asking is beyond what a beginner would be able to solve on their own
i.e. asking that question implies it probably belongs in #๐ปโcode-beginner, if that makes sense?
Also it is pretty common to get defensive when someone is doubting your capability with no knowledge of the actually problem, instead of trying to be helpful.
he didn't do that at all dude, you've just gotten yourself so worked up and twisted it all
they litterally did
not here to argue - good luck with what you're trying to do
I said it is, they said they doubted my statement with no knowledge of my problem
thank you
would there be a reason why Vector3.Angle() would always return 0?
even when its Vector3.Angle(Vector3.forward, Vector3.zero)
I am using the following code to jump, but if there is an object with a rigidbody on top of the player, the player barely jumps. The more objects I add on top of the player, the less the player jumps. I have tried setting the rigidbody mass to 0.0001 but it didn't help. Any ideas?
rb.velocity = new Vector2(rb.velocity.x, jumpForce);```
use rb,AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse) instead
its agnostic to the current object's velocity and its surroundings
Same result
well it would make sense why it would make it harder when its adding velocity to its self and the objects above it
why would there be other objects on top of the player
if its only one, and one only, or even more, I would just also add upwards velocity to the other objects on top of the player
The player controls multiple objects, its a puzzle game
oh
then just give them also upwards velocity
does the puzzle involve the player balancing these objects on top?
I just started using dictionary variables for the first time, and I feel I'm lost on some basic understanding of how to use them.
I have a dictionary of keys. The keys are just strings of id numbers. "1", "2", etc. The values are small lists. Lists of two strings. I have a for loop adding these, and printing out what it's adding.
I'm trying to then access some of these values, and it's just not working. I've tried a bunch of things, one of them is commented out.
foreach (CardXml card in deckXmlFile.mainDeck.Cards)
{
currentDeckList.Add(card.id);
tempNameList[0] = card.name; tempNameList[1] = card.pairName;
Debug.Log("Added: '" + card.name + "' and '" + card.pairName + "' to the dictionary at Id key = " + card.id);
try
{
cardNamesDictionary.Add(card.id, tempNameList);
}
catch
{
Debug.Log("Error importing the deck list. An element with Card Id: '" + card.id + "' already exists. Was it duplicated in the file?");
}
}
Shuffle(currentDeckList);
Debug.Log(currentDeckList[0] + ", " + currentDeckList[1] + ", " + currentDeckList[2]);
//List<string> value = GetNamesFromId(currentDeckList[0]);
List<string> value = cardNamesDictionary["3"];
Debug.Log("Card Name: '" + value[0] + "', Card Pair Name: " + value[1]);
value = GetNamesFromId(currentDeckList[1]);
Debug.Log("Card Name: '" + value[0] + "', Card Pair Name: " + value[1]);
if not, just freeze the all the objects
make all the objects on top of the player not use gravity
if they're on top of the player
once the player lets them go, give them their normal gravity
No matter what value I try to grab, it always prints out the last one. I never gives an error.
https://gyazo.com/39c6112a0ef2a2cc82686ae45562441a
Let me show you lol @unkempt sail, I explained it horribly. Give me a minute
alr
mine was controlling multiple players in a game called "you're a clone`
What a coincidence lol
one of the puzzles involved a clone jumping on top of one of the other clones to get a jump boost
let me see what I did when they were on top of each other
in my jump method I calculate the destination height of the jump and while the transform hasn't reached that height I add force upward
yeah I just made the other players kinematic
but I don't think that would quite work since you're controlling all the enemies simultaneously
seems like a good idea, but rigidbody calculations would break correct?
I'm using RB and addrelativeforce upward
Hmm
destinationY = transform.position.y + maxJumpyY;
while (transform.position.y < destinationY)
{
_pcRig.AddRelativeForce((transform.up * trackSettings.JumpVelocity) * Time.deltaTime * 5, ForceMode.VelocityChange);
yield return null;
}
but that velocitychange mode might be off from what you're using, but it guarantees I always jump to that height
its weird that all the objects don't jump together tho
Should I ask this in another chat?
you're applying the same force to all of them, why wouldn't they just synchronously jump
try using a List and see if you encounter the same problems
Wdym?
moving from arrays and lists to dictionaries or hashsets can be tricky
I've been using lists a lot, those work just fine
use a List<> instead of a Dictionary<>
I'm specifically trying to learn how dictionaries work
can you show your dictionary definition, is the key a string or an int
like what is this supposed to be List<string> value = cardNamesDictionary["3"];
Dictionary<string, List<string>> cardNamesDictionary = new Dictionary<string, List<string>>();
The keys are strings, the values are lists of strings
k so you are using it correctly
if the key of the index is just a number why don't you use an int key instead?
I don't see why that matters right now
make the debug easier for your self
Alfy please stop. You are simply judging my style of coding and you are not helping.
guess beginner might be better to ask in I'm not sure
There is a reason I'm using strings as the keys, they are just numbers right now.
also string keys are much slower then int keys
omg stop alfy
yeah it's fine I was just trying to follow along to verify you were doing it right
nah I ain't stoppin
try debugging and adding a break point at the point where you're adding cards
maybe its just adding the same card over and over somehow
Hmm, that could work..
Alfy I have repeatedly asked you to stop being so rude, and simply judging what variable type I'm using. I'm calling in moderator help.
Trae, just trying to understand the problem, you're saying cardNamesDictionary["3"]; debugs out the wrong card?
Yes
It's because they can only jump on the ground. Let me make them be able to jump on cats, that may fix it
That works ๐
there you go
just don't make it so that players identify each other as ground
that could make some problems later
try making a different var like onOtherPlayer
Yeah, they can infinitely jump now lol
good job
How should I fix this
It is detecting the same cat as a cat under it so it can jump in air
how did you set up the collisions?
Why do people use Physics2D.OverlapCircle to check for ground instead of raycast?
from my experience raycast can be a bit problematic if the player is a bit under the map for some reason
Yep
Ah, but the player shouldn't be under the map
cause there is a better chance to detect ground with a circle instead of a line
I see
some people still use a specified collider for ground detection
Can Physics2D.OverlapCircle tell me the object it overlaps?
Ohh it clearly says Collider2D
lol
and even a List of them if you want multiple
i do raycasts cause I have a different animation if you're above a certain height during a jump (glide vs landing anim)
How?
it returns an array of colliders
Physics2D.OverlapCircleAll
Thanks
not even needed, overlap circle has diff signatures
I like to use the explicit declaration because confusion
if you're always getting input from the player so they can jump, I'd recommend using a timer instead
Collider2D[] collider = Physics2D.OverlapCircleAll(groundCheck.transform.position, 0.2f, collidableLayer);
for (int i = 0; i < collider.Length; i++)
if (collider[i].gameObject != gameObject)
return true;
return false;```
This fixed it ๐
think they need to debug.log card.id when they add it to the dictionary as well, verify it's what they think because cardNamesDictionary["3"] is giving a different card than they're expecting
{
BGM.clip = music;
if (BGM.clip != music)
{
BGM.Stop();
BGM.clip = music;
BGM.Play();
}
}
The above is in my Audio Manager
{
if (BGM.clip == music)
{
return;
}
BGM.Stop();
BGM.clip = music;
BGM.Play();
}
Or alternatively even this above one could be my audio Manager. (Both dont work)
private AudioManager theAM;
public void Awake()
{
theAM = FindObjectOfType<AudioManager>();
if (newTrack != null)
{
theAM.SwitchMusic(newTrack);
}
}
This is in my music script
The Audio Manager also doesnt destroy on load. Does anyone know why this wouldnt play the music from my Music object, in the Audio Manager's BGM.clip?
I had a different code before but it wasnt working, so I changed it because it was just too confusing for me. Now this new code also isnt working. I'm very confused why. Its been days that I've been working on this.
check for errors, start using Debug.Log in stuff
how about
[SerializeField] private AudioSource backgroundMusic;
public static AudioManager Instance { get; private set; }
private void Awake() {
Instance = this;
}
public void SwitchMusic(AudioClip musicClip) {
backgroundMusic.clip = musicClip;
backgroundMusic.Play();
}
for the second
public AudioClip newTrack;
public void Start()
{
if (newTrack != null)
{
AudioManager.Instance.SwitchMusic(newTrack);
}
}
I'll try that.
Thank you!
THIS SUPER HELPED
But for some reason the music doesnt continue if it is the same song.
try looping the audio source
THANK YOU!!!
np
good job
(damn just asked a question in another chat but I'm getting to parts of my game where I'm a bit lost in haha)
So I've seen it's not very good to make your world go to high numbers as higher out, the more incorrect calculations happen or something..
How do people tend to deal with that? Using some sort of world streaming system?
My world is going to be large (as it's going to simulate a star system) so I'm wondering if I should have a world streaming system and every warp would kinda have the illusion you're moving but you aren't.
Not sure how people go about this tho
outer worlds made the world move around the player somehow instead of the other way around
That is crazy lol
yeah for super massive scenes they move the environment and the camera stays at origin
My game has the benefit where you'll mainly be warping to travel to far out areas
then you could just launch another scene you warp to and reset the origin
I would but 100 star systems + up to 8 or 9 scenes per system seems overkill haha
maybe try making everything 10x smaller?
lets say that the biggest object would be at scale 1
and everything else would be comparatively smaller
on way is to divide your world into grids. jsut like how you hopefully dont have 10000 square km in one scene, you actual position doesn't need to be spanning 10000 km range. Keep everything in worldspace relative to a current local area and the "real" position as a combination of the world space as well as the large grid offset for your larger world
Basically chunk system ala minecraft?
yeah esactly
Someone did bring that up to me
realistically you shoudl not have an ovject that is 10k miles away loaded at any times anyway
When you move into the next grid does it move you back to 0,0,0
so you need a definition of "position" that is different from unity's world space
yeah
So instead of chunks I could handle it via "warps". And just load the grid around the warp each time. Then when I warp to another location I can poof you to that warp's area etc.
it would be sick if unity started using doubles instead of floats
I read about that. But it introduces performance issues iirc
there's lots of benefits to floats, but its getting less over time
unity was built on float bostly because of device limitations at the time
Ahh yeah that's true
but there's lots of ways to work around it, and really, your world "model" should not be calculating positions based on unity's definition of worldspace
unless your'e working onf a very small scale
I guess switching to doubles would probably take a bunch of time to change everything to support doubles
specially the rendering
yes absolutely
It's my first time experimenting with large scale worlds but I'm basically doing this as a huge programming challenge lol
not like its a find a replace operation
I like eve but I wished it were single player and therefore my project exists lol
@wintry grove what scale are you workign on like universe scale, planet scale
how big do numbers get
Planet scale if we're talking about warps. Like huge planets in the background.
With the ability to warp around the star system
So basically illusion to fade in / contort time then poof to next station
What do you mean in regards to finite?
Oh no
can you shrink to ant size
Its entirely in space
okok
So it's easy in that regard
The ships will be the smallest things
And planets will be nothing more than skybox illusions
it sounds like you want like 2 scenes, one for space and then a separate scene for each ship
and the scale on each scene is very different
are you familiar with LOD
What would the purpose be of ship specific scenes?
I'm planning on fleets btw not just individual ships
well, you can make one scene the entire space at low detail, so maybe 1000 units across in unity units
but then make a ship also 1000 unity across in unity units, but obviously you experience it differently
so different scene can define the sence of scale
I did see someone use camera illusions for scale
Are you meaning something similar to this?
yes similar, except a skybox is never part of the world
if you want to be able to visit and fly around planets and moons you would need to do somethign a bit trickier
Ahh. I wouldn't intend for that
I'm keeping eve's style where the planets and moons are visible and large
But never more than something in the distance
well then yes a skybox is perfect
you just want a giant open area in space to fly around in?
ok yeah, then that videowould explain how to do wha tyou want perfectly
But it'll all be done in space
skybox is goo because you can make it very details with a very small scale map
Yup. It's very good for making illusions
yes
Appreciate the talk I have a more direct approach on how to tackle this haha
i suspect you'll still run into this problem sooner or later though, so check out this article https://docs.unity3d.com/Manual/LevelOfDetail.html
I still have to figure out simulating AI ships doing things when they aren't loaded XD
Oh yeah LODs
Further away = less rendered right
Up close = more detail
you have different meshes that will swap out when things move in and out of range
Ahh gotcha gotcha
for anything you can ac tually get close to liek other ships or asteroids, it's good to do
Gotcha. Yes that would be perfect to learn I'll bookmark this
Appreciate the talk! I have a more direct understanding of this now
how can I check if a collider is colliding with another collider? none of them have rigid bodys
OnCollisionEnter
needs rigidbody for any of the collision callbacks
you can't detect collision without a rigidbody? I thought you only needed that for physics
OnCollisionEnter/OntriggerEnter need rigidbody to fire
Note: Both GameObjects must contain a Collider component. One must have Collider.isTrigger enabled, and contain a Rigidbody. If both GameObjects have Collider.isTrigger enabled, no collision happens. The same applies when both GameObjects do not have a Rigidbody component.
i guess i've just never done that. Good to know
it's common people asking why it's not working and it's because they don't have a rb
https://docs.unity3d.com/Manual/CollidersOverview.html
I highly recommend fully reading this page twice
And later on you can just refer to the last table ๐
Will do Thanks
Anyone got any experience using Microsoft.Data.SQLite.Core or the custom SQLite PCL bundles from UnityNuget?
just wondering if you can use one of the bundles with Microsoft.Data.Sqlite.Core, like SQLitePCLRaw.bundle_e_sqlite3 since it says it doesn't include the native library with it, or if you just include the library in the plugins folder for unity to pick it up
Hi there!
I'm having trouble with my editor preview system. Whenever i set a color on the same sprite on a custom tile the colors merge I have provided in the video what is happening, here is my script:
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.Tilemaps;
[CustomEditor(typeof(LevelTile))]
public class LevelTileEditor : Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
}
public override Texture2D RenderStaticPreview(string assetPath, Object[] subAssets, int width, int height)
{
Tile Target = (Tile)target;
if (Target.sprite != null)
{
Texture2D newIcon = new Texture2D(width, height);
Texture2D spritePreview = AssetPreview.GetAssetPreview(Target.sprite);
Color[] pixels = spritePreview.GetPixels();
for (int i = 0; i < pixels.Length; i++)
{
pixels[i] = pixels[i] * Target.color; // Tint
}
spritePreview.SetPixels(pixels);
spritePreview.Apply();
EditorUtility.CopySerialized(spritePreview, newIcon);
EditorUtility.SetDirty(Target);
return newIcon;
}
return base.RenderStaticPreview(assetPath, subAssets, width, height);
}
}
Thanks!
https://youtu.be/DDmfiAXJTvs https://paste.ofcode.org/34vyJYipXB8mfqCwicVHrWu Parallax script, but not working properly. It seems to be behind and merging with other things. problem is I used 3d parts when the tutorial called for 2d images, but I made alterations. Please help
whats the best way to handle a ton of rigidbody items
i have a script that turns off the rigidbody if it gets too far from the player
but it checks distance on update and i suspect its losing more performance than it saves
i could give them all unity LOD but i cant really because LOD group doesnt support multi object editing for some reason
have you actually profiled this?
make sure you are using square magnitude instead of magnitude when checking distance. sqrts are expensive
No point in guessing. Hundreds of RBs should really be fine. Profile and see if you actually need to do any optimizations. Majority of the time reducing polygons, light baking, etc. will have a much higher impact on performance than the code. I would start there first.
But the definitive answer is: Profile.
i just used vector3.distance in that script
That just calls (a-b).magnitude, which has to do a sqrt because that's how math works. Just do (a-b).sqrMagnitude
Then check that against your distance threshold^2
But also just profile it
yeah im on it
So there's an Application.persistentDataPath, as well as an Application.temporaryCachePath. Is the CachePath cleared when you exit or something? Or what's the deal with that?
We create a directory path where temporary data can be stored, but how temporary is that?
@lusty hollow I don't think there is a clear answer on that. If you have data that can be temporary I'd probably just put it a tmp dir in the persistentDataPath and delete it when the game starts and exits.
Alright! Thanks for the answer Nashville. Maybe I will test some things out myself. ๐
If you want to use temporaryCachePath I'd be cautious and never assume that something is there, even if you just wrote to it
Hey I tried some googling but I couldn't find a simple way to word this question that would yield an answer. I have a class with some properties and a List of objects in that class. I'm wondering, is there a way to iterate through each item of that list and see if any of the objects of that class have a property equal to some value I designate? i.e. something like the pseudo code below
list objects;
bool objects_property_contains_number_5 = objects.property.Contains(5);
return(bool)
to tell me whether any of the objects in my list have some property "property" = 5
for loop
yea without going through each value individually
like some inbuilt function to check the properties of a list
?
but that loops through all the items as well
right
you don't have to make the loop though
i don't think there is anyway around looping through the list
yea well I wanted to avoid that cause optimisation but I guess I can just loop through and break when I find it
sorry not thinking clearly today
there is also List.Find that will find the first one in the list
ty
how big is the list?
LINQ should help you
any time you query the list it is going to loop through the list right? He wanted to avoid looping the list for some reason.
If you're going to be accessing your data frequently by some key other than "index in list", you might be better off using a different data structure than a list
For example a Dictionary
Your original question is pretty vague though, and seems contrived with this number 5 thing
How do i get concrete types of generic Types by reflection?
For example i want to find all concrete MyClass<T> Types like MyClass<int>, MyClass<float> etc...
assembly.GetTypes() will only get me something like "MyClass'1"
is it even possible?
MakeGenericType
i dont need to make them. i need to find all Types defined in the assembly to display them in a dropdown in the editor
oh, misread. Why not use IsSubclassOf? should be something along the lines of assembly.GetTypes().Where(ti => ti.IsSubclassOf(typeof(MyClass<>));
if it's editor only, you maybe want to use TypeCache.GetTypesDerivedFrom instead of assembly.GetTypes(), I'm not 100% sure it works with an open generic type though since I've never tried it for that purpose