#archived-code-general
1 messages · Page 346 of 1
Those would be providing the Y inputs
pedals did nothing.
Hey, how do I check if I'm on mobile (Android) or PC (Windows, Linux) using the #if statement? I could only find UNITY_STANDALONE and UNITY_STANDLONE_WIN and PLATFORM_STANDALONE and PLATFORM_STANDLONE_WIN, but I'm not sure what they do.
UNITY_STANDALONE_LINUX, UNITY_STANDALONE_WINDOWS, UNITY_ANDROID
They don't show up for me. Will they still work, or do I have to change something in the player settings?
I don't think you're going to see all of these symbols in the autocomplete list
If a symbol isn't defined, C# doesn't have any clue that it could ever possibly exist
if in doubt look in Assembly-CSharp.csproj
Alright, thanks a lot of the help 👍
do you have any other ideas to why i would be giving a phantom input?
i also can send a video of what the player is doing when I press play.
nevermind, finally fixed it. only took 6 hours
hey im trying to procedurally create a terrain mesh but am having an issue with it not rendering the mesh when i increase the depth or width like theres some sort of limit to the amount of triangles it can render.
heres my code https://pastebin.com/Xqh6zekY
as you can see in the image below 256x256 works fine but as soon as i go over that it doesnt even though its still generating the triangles.
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.
nevermind didnt realise there was a limit on mesh vertice count 😭
You need to switch the index format from 16-bit integers to 32-bit integers
hey guys, I'm trying to make a simple curved world, and I already made a shader to achieve the visual result, but I'm getting some issues with the trigger collider I'm ussing to put another gameobject of my pool in front of the other piece together, I have some printscreen, but:
- I can handle different to achieve that?
- or maybe exists a simple solution for that?
You have not stated what the problem is.
the problem is to set correctly the position, as you can see, the colliders are getting pretty close one to the other, it's strange to work like this, with a anchor point far away to the road curved
I'm just looking for more consistency
If everything uses the curved world shader, then it'll work out correctly.
actually the road segment it's a prefab, all with the same default material with the shader
all of the game logic will work on a straight line
the visuals will just get distorted
but look, why I'm getting different location at my colliders of the same prefab?
I change the values to not curve to show it
Get rid of the curved material entirely to make sure.
well, I'll stay with this solution, and try to adapt
Also, I'm not sure what you're expecting to see here.
I was just wondering if this is a really good solution, or maybe I should try something different
because the shade make not so easy to put all pieces together to achieve a infinite curved road
Using a shader to make a "curved world" effect is reasonable. I've done it before.
you just have to remember that this has no effect on anything other than the visuals
So you will see the visuals "detaching" from your objects
And there are some cases where you do have to manually move objects to match the shader curve
For example, if you have lights, those need to be moved
but probably I'll get some issues to fit the pieces right?
uOffset = (adjPos.x % tilingFactor) * tileSize;
vOffset = (adjPos.y % tilingFactor) * tileSize;
break;
case Direction.East: //X+
uOffset = (adjPos.z % tilingFactor) * tileSize;
vOffset = (adjPos.y % tilingFactor) * tileSize;
break;
case Direction.West: //X-
uOffset = (adjPos.z % tilingFactor) * tileSize;
vOffset = (adjPos.y % tilingFactor) * tileSize;
break;
}
uvs.Add(new Vector2(uOffset, vOffset + tileSize));
uvs.Add(new Vector2(uOffset + tileSize, vOffset + tileSize));
uvs.Add(new Vector2(uOffset + tileSize, vOffset));
uvs.Add(new Vector2(uOffset, vOffset));``` left some cases out to make the message shorter, how can i correct the offsets for z- x+ and y-? this works fine for the other 3 directions
Fit the pieces together completely normally, as if it were a straight track.
Assuming they're all being distorted in the same way, they'll still fit together
For example, if I have 3 sounds in my scriptable object, and I go through each of them, increasing the index, gameobjects are returned, however, they all are the last audio clip that was input.
audioQueue.Add(soundFXHandler.GetSound2DRaw(inputMusic.Sections[0].ReadAudio())); audioQueue.Add(soundFXHandler.GetSound2DRaw(inputMusic.Sections[1].ReadAudio())); audioQueue.Add(soundFXHandler.GetSound2DRaw(inputMusic.Sections[3].ReadAudio()));
but Idk why, they don't, if I fit perfectly withou a curve, when I try to curve, the position doesn't fit perfectly, but I'll study about how can I handle this
any ideas?
I don't know what "doesn't fit perfectly" means.
I mean the object road put in front of the other object, doesn't fit in the position, and I was trying to adjust manually
but seems annoying
If they line up with the curving disabled, and your curving shader is written correctly, they'll still line up when you turn on curving
Hello, im building a little popup message and I wanted to know how to target this task:
- Using a singleton to access the functions from any class (I already have a few and I think I shouldnt have too many but idk)
- Using a static class (I think its not possible since I need to attach a prefab somewhere, explanation below).
- Attaching the script to the canvas and calling it a day.
- Something else Im missing.
I either can render the popup to an existent canvas or create a temporary canvas from code and render it there, but I 100% need to be able to have the popup panel (background, buttons, etc) in a prefab.
Which solution should I pick?
It's not supposed to have a lot of singletons, but it really depends. You can use events. I'd prefer to have an event invoked, and in the class where I need to use it, I just subscribe.
But is it possible to attach the prefab to a class that is not assigned to a GameObject in the inspector?
yes, for sure? just a prefab?
ye
you can use a gameObject or Transform reference serialized to put your prefab
and in the code I should put the name of the prefab as string?
like,
void Awake()
{
prefab = GameObject.Instantiate((UnityEngine.Object) Resources.Load("Popup"), Vector3.zero, Quaternion.identity);
}```
wait a minute
sure
you can't make like this
as I can see, you want to instantiate a resource for your project
right?
Yes, an UI element in this case
its a popup confirmation window,
"u sure?"
"yes/no"
and then i pick the resulting bool
and perform x action
ok got it
maybe it's a lot of easier for you, just have a Canva with Modal object and set active, when it's necessary
Two vertices at the same position on different objects should wind up at the same position after the curving
I know how to make it work, i just dont know wich approach is the best in order to keeping the code clean and logic
maybe, I'll need to check this
One issue could be if this is an HDRP game: it uses camera-relative rendering by default
hence there being the Absolute Position node, which isn't camera-relative
it's urp
for me, the best aproach it's make an UIManager
and then handle all types of menu inside my game
Yeah, I have a small addiction to singletons
ok, cool
So, another one cant hurt, right?
now, it's good to have a canvas for this modal popUp and active the reference
nah, but I think this time you don't need it
maybe i should just stick it to the screen manager?
in MyScreenManager you can handle
alr
yw
I have a method which creates a new audio source with a clip. When calling this method through another script multiple times, it sets all of my clips to the most recent time I run the method.
Why could this be?
show the code
It could be that your code has a bug 🪲
Has anyone encountered such a problem?
{
AudioSource audioSource = GetAudioSource();
if (audioSource == null)
return null;
audioSource.name = clip.name;
audioSource.spatialBlend = 0f;
audioSource.clip = clip;
return audioSource;
}
private AudioSource GetAudioSource ()
{
foreach (AudioSource source in audioSources)
{
if (!source.isPlaying)
return source;
}
if (audioSources.Count < maxSources)
{
GameObject newAudioSource = new GameObject();
newAudioSource.transform.SetParent(transform);
audioSources.Add(newAudioSource.AddComponent<AudioSource>());
return audioSources[audioSources.Count - 1];
}
Debug.LogWarning("No available audio sources found and maximum number of audio sources reached.");
return null;
}
This error happens when I try to run this under start:
audioQueue.Add(soundFXHandler.GetSound2DRaw(inputMusic.Sections[0].ReadAudio()));
audioQueue.Add(soundFXHandler.GetSound2DRaw(inputMusic.Sections[1].ReadAudio()));
audioQueue.Add(soundFXHandler.GetSound2DRaw(inputMusic.Sections[3].ReadAudio()));
Looks like you're using Unity Physics or Havok or something?
I am almost certain that the error is not what is being passed into it, but instead how it is handled
I'm using Unity 6, so
😶🌫️
I attached my code in the message above. It should function as intended, however I still get this issue. Do you happen to know why this may be?
Are you using this in 2d? Like on a canvas or something?
3d. But, I recently migrated a project to WebGL. Is CharacterController not supported in it? I haven't found any information about it, plus everything works on other platforms...
CC works fine on webgl
Well, this is sus
I think you are!
Show me your package manager window.
oh yeah, you can also just look in the "Physics" section of the Project Settings, it looks like
it looks like unity 6 rearranged the menus a bit
you have no physics engine selected at all
Hm, so that's what they changed
well ofc its not working 😛
you may have switched it by accident, since I doubt that the default is now "no physics
"
yeah def not default
Nice
Oh, yeah, it's working now
Thanks 🙏
Oh you cross posted too. Read the #📖┃code-of-conduct please, this is just spam
This is a very common approach that should work for you
You could consider using a constant seed for debugging if you want to make the process a little easier
Nice, good luck with it!
@heady iris I remade my shader, now it's working fine
nice (:
tysm for the support
If you want to put lights on the track, you'll need to implement the same bending logic in C#
(or anything else that you can't bend with the shader)
make sense, for now I'll prototype some others aspects and work with lighting when I'm in the polish state of this project
lighting turned out to be a major pain in the ass for other reasons
the lights wouldn't light up the track properly if it was curved far enough
because Unity thought that there was no way for the light to affect the mesh at all
I need to go re-visit that
god damn
well, maybe I can afford of this, it's just a mobile game, I want to make it simple
but decent
For a mobile game you probably don't want to use realtime lights anyway
maybe I can create a fake lighting in the road editing my shader
they also wound up being kind of ugly lol
I'm not sure
probably I don't need any shadows, just some bloom's to get nice visuals, do you think this will cost a lot of my performance?
cool, I'll check on old devices to take an idea
thanks again
using unity relay, I get a 404 everytime I try to connect with the code.. even though the code is correct
https://forum.unity.com/threads/relay-troubleshooting-join-code-not-found.1278065/ everybody just says "same" and has no solution, does anybody know?
sounds like the code is wrong, then
or you have some other configuration that is incorrect
e.g. you need to change something in the cloud dashboard
you should ask about this in #archived-unity-gaming-services
the code is right unless there is some invisible character being injected but i have it joining by getting the room code from the lobby data
oh right it got cut off
Note that a 404 would not be the expected response for a bad join code
you'd expect a 403 (Forbidden)
404 join code not found
thank you 🙏
here's the last time it traced back to my own code
really doesn't give me any information
show your !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.
Which part would you like to see?
The entire LobbyManager script.
how does GetJoinCode work?
public async Task<string> GetJoinCode()
{
var code = State.CurrentLobby?.Data["joincode"].Value;
if (State.CurrentLobby?.Data["joincode"].Value == null)
{
await RelayService.Instance.GetJoinCodeAsync(State.CurrentRelay.AllocationId).ContinueWith((task) =>
{
code = task.Result;
});
}
return code;
}
the if statement is for when the relay is first created
As far as I know, the problem isn't with the join code
On both ends they're identical (at least from what I see in the logs)
yeah, I'm not seeing anything obvious
rn i'm digging through utp transport stuff, i'm guessing i missed a step somewhere in the setup/connection
This should be separate from the actual transport that'll be used for gamepaly
since this is just requesting a Relay instance and then connecting to it
i saw something about binding a driver but then another message under it saying that you don't need to do that anymore
https://docs.unity.com/ugs/en-us/manual/relay/manual/relay-and-ngo
the example here only configures your transport to go through the relay server after JoinAllocationAsync succeeds
I should mention im using Mirror
maybe i'll find an example that shows me what im doing wrong
anyone got any clue as to why i get this weird camera stuttering when looking left and right? its only in the editor
are you rotating a rigidbody?
fast ass save times
that means the log file is taking more storage 💀
you may still want that -- are you moving the camera in Update?
if so, do it in LateUpdate instead. Interpolation happens between those two messages
If you're using a cinemachine camera you can change the update mode
i dont think i even need interpolate on so should be all good as is
I'm just going to try and bruteforce the order I do things in maybe that'll fix it
well, trying to start the client/host THEN join the allocation
anyone know how to change the UV scaling and offset values through code? I'm not seeing it in the shader script for LitTesselation
hit Select Shader in the material's little ... menu
this will let you look at all of its properties
im having a problem, i followed the brackeys tutorial using player controller for 3d player movement, https://gdl.space/vuborozike.cpp this is my code, but the problem is when i go backwards then its kindof funky, and when i jump backwards and move my mouse downwards then i go really high, and when i point my mouse down then i cant jump at all
thats a lot cleaner, but im still unable see the values im looking for. is there inheritance or importing values in hlsl?
Show what you're seeing in the inspector.
Don't crosspost. You just asked this in #💻┃code-beginner
my bad
I understand the difference between a double and a float with a few exceptions.
Does defining a variable like this have any impact? Do I need to always suffix these numbers with f?
float foo = 1;
In examples similar to the below mentioned, is the number 1 getting compiled differently? Is this format to my disadvantage?
float foo = .5f;
foo += 1;
float bar = .5f;
bar = foo + 1 + .5f;
Is there any reason as to why I should put the f after a "whole number" float?
pretty sure f at the end is a static cast so itll happen at compile time. if you do something like 3/4 and no static cast it'll assume integers so you truncate
@heady iris its the LitTesselation shader in the hdrp folder. I can upload it here
I want you to show the inspector after clicking "Select Shader"
I saw that BinaryFormatter is bad idea, does it refers to every binary saving? And while I have many large arrays of integers (mostly byte) what is good and fast way to serialize that?
it refers specifically to c#'s BinaryFormatter class and the other classes that use it https://learn.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide
There is also a section half way down for good alternatives (and bad ones too)
It's not as bad as, say, Python's pickle module
I was TAing a cryptography class in grad school
The students built a networked application for their final project (then tried to break another team's project)
I used it to pop calc.exe on one team's computer
thanks, Ill see these alternatives
You can literally just tell it "run this command"
BinaryFormatter is still vulnerable, but it's more convoluted
https://youtu.be/msPNJ2cxWfw?si=xAhLmHi-KsE6gWQe&t=637
I think this might've answered my problem (timestamp embedded)
❤ Watch my FREE Complete Multiplayer Course https://www.youtube.com/watch?v=7glCsF9fv3s
✅ Learn more about Relay and UGS https://on.unity.com/3tQZLLW
📝 Relay Docs https://on.unity.com/3OjXL8z
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👍 Learn to make awesome games step-by-step from start to finish.
👇 Click on Show More
🎮 Ge...
I forgot that gravity is negative XD
Hey, i'm trying to detect if I can spawn an object in without it overlapping another, I have this code written: transform.position = new Vector3(worldPos.x, 30f, worldPos.z);
Debug.DrawRay(transform.position, Vector3.down, Color.yellow, Mathf.Infinity);if (Physics.SphereCast(transform.position, 1f, -transform.up, out hit, 1000f, whatIsInterior))
{
but it doesn't seem to find anything, is there something I am doing wrong?
did u try changing the size of the cast already
I switched back to netcode for gameobjects and it was easy enough to set up, mirror is just too finnicky
worked instantly
(it won't let me take a two monitor screenshot)
yeah i tried making it small and large and both didn't make a difference
how do you know it's not detecting anything
does the object expected to be hit have a collider
I've added a print into the If statement and it never prints anything
Yeah the object that is spherecasting and the object getting hit both have a collider
is your game 2D
3D
use the physics debugger and see whats happening to cast
there's a physics debugger? o-o
oh my god there is
its been there for a while lol
they just recently as of 2022 added a Queries debugger, no need to draw gizmos anymore really
Hey guys I'm trying to rotate a cylinder forwards (when I press W), but the cross product of vector up of the game object and vector up of world sign gets flipped when the object rotates. I'm wondering what I'm doing wrong here?
are you perhaps trying to use euler angles
Using radians
have you debugged what the values you're sending in are? what issue is this actually causing because this sounds more like you aren't using the result of the cross product in a valid way
also not even sure what euler angles or radians have to do with that because a cross product has nothing to do with rotation
Thing is the camera can rotate
so I get the dot product to know which side of the object I'm on and apply the input accordingly
maybe take a moment and actually describe what the issue is, because this seems like it has nothing to do with what you described above.
Guys, does anybody know how I can rotate the player (ship) using Rigidbody.MoveRotation instead of Transform.Rotate?
https://gdl.space/agakelejih.cpp
Hey, small question!
I need to run some logic pre-build (precisely, fetching some ScriptableObjects and assigning some Data to them), and i'm wondering if OnPreprocessBuild is the proper thing to hook into?
Nvm, i think it's BuildPlayerProcessor and PrepareForBuild
Can anybody tell me about how Toggles are supposed to work, and more specifically how OnToggle is used and where it's referenced?
where are you seeing anything called OnToggle
it's code I wrote a long time ago so I'm just trying to figure out what I even did** **
somehow a toggle with no references to this function manages to call this static function I wrote in a script
public static void OnToggle_Processing()
you'll have to show the context for this if you want anyone to interpret what it does. just showing the signature doesn't help at all since this is some method that you created
at a guess though, I'd say you probably subscribed to the toggle's onValueChanged event with that method
how can i make a collider with a set of points?
2d or 3d?
2d
A collider has a bounds property. You can use that to set a size or mix,max positions
pauseOptions = MenuController.pauseOptions;
Debug.Log(pauseOptions);
// - Graphics -
toggleE = pauseOptions.transform.Find("toggleEffects").gameObject;
Debug.Log(toggleE);
toggleEComponent = toggleE.GetComponent<Toggle>();
Debug.Log(toggleEComponent);
// v
preferencePrAll = PlayerPrefs.GetInt("DisablePrAll");
Debug.Log("Read PlayerPref 'DisablePrAll' with value (" + preferencePrAll.ToString() + ").");
switch (preferencePrAll)
{
case (0):
Debug.Log("Case (0) iterated.");
toggleEComponent.isOn = true;
MenuController.ProcessingOn();
break;
case (1):
Debug.Log("Case (1) iterated.");
toggleEComponent.isOn = false;
MenuController.ProcessingOff();
break;
}
This is how the toggle is obtained currently.
the function it's calling, MenuController.ProcessingOn()/Off() respectively, just disable one gameObject
and it's unrelated to this script
it also contains no references to this
paste the whole class in a bin site 👇 !code
at no point is that method you were asking about shown here
📃 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.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
hastebin has been doing that a lot lately, it should appear in a few minutes
but use a different site if possible. hastebin has gotten terrible since toptal acquired it
lmao i just got ip banned from the site due to rate limiting for refreshing a couple times so even if the link does start working i won't be able to see it
oh god everything is static 😬
but none of those methods are being used in this code so you'll need to use your IDE to find out where they are actually being used. and since it's all static none of it is being set or subscribed in the inspector
I was worried you would say it was that bad lmao
let's just say I didn't learn to code by making a game, but I did learn CS that way
Do you have more than one copy of that object?
It's pointless to have private static objects if you do not intend to share references between object instances
It's uh self-referencing in a way
you probably don't want me to get into all that, it's even worse
actually it's quite simple I can probably summarize it
basically I don't think I ended up using scriptable objects to make my game's objects (the player, hud elements, etc.) scene-consistent and also persistent in cases where the objects are destroyed, I uh.. yeah, I made everything static and that seemed to solve most issues
But if you are destroying everything, you'll have to repopulate all references anyway with new ones
exactly! I had the same epiphany, I decided to use a "cache" scene, so that in one instance of the game session it only needs to instantiate once, and then a global persistence system I made carries the same objects between scenes
they're just not scriptable technically
this requires weird workarounds
Is there any equivalent to AssetDatabase.GUIDToAssetPath on runtime? I have a imagelibrary I need to access through runtime, but the library itself is only providing GUIDs.
Put the images in an array and use an index as as an ID.
Hi
Why when I enable obfuscate my list elements are null? List is not null, only elements of list
They are already an array. But I just found out, you got a little checkbox on that referenceimagelibrary to keep the images on runtime, so .texture already returns a texture instead of GUID. 🙂 Thx anyways tho!
does IL2CPP-generated code mean you can not detect null errors without a ton of extra code affecting performance? This was easy to catch in mono but I guess c++ land does no such thing!
It depends on the build configuration and wether you're making null checks explicitly
why do people use the abstract keyword on scriptable objects classes?
I think this belongs here, tell me if this is more something for #archived-code-advanced
I have my own API and i want to have my own Player Feedback System ingame.
I already have an idea how to set that up, doesnt sound too hard.
Now i also want if there are bigger errors or execptions to not start the unity Execption / Problem thing, but to start my own automated system that sends that to my API with their Account name, Machine Information, The Point where it crashed and the Stacktrace.
How would ago disabling the Unity Error Popup / Window and replace it with my own code / access the Error stuff ?
well yes - debug build is equivalent of adding tons of code to check things! But I could add explicit checks for debugging always
Yeah. But you're typically not supposed to get null reference in a prod build. That would mean that you failed during development and QA
for sure - but have to test for it during dev
To have abstract classes. Same as non SO.🤷♂️
IIRC abstract classes are classes that are used as a base class and can be extended upon
right?
Any class can be a base class (any class can be inherited unless explicitly sealed - OOP). You cannot create instances of abstract classes.
It explicitly ensures that no one attempts to create an instance of it
Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes, not instantiated on its own.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/abstract
It's for explicitness like keywords private, const, readonly and whatnot.
ohhh so for example if i have a GameManager script i should make that abstract?
Only if you do not want anyone (including yourself) to create an instance of it. You can create an instance of something that inherits it but not it specifically.
ok thank you for the short explanation!
hi, can someone help me, i have a cube, who normally jump when spacebar is clicked, it function is call, but nothing happened :
What's the JumpHeight's value and where is the method Jump called?
Also I hope you note that you Rigidbody's mass is 100
the Jump Called is un the Move corposant, and the jumpHeight is at 10, but whatever the value, the cube don't jump
Where is the Move method called? In Update?
Consider changing the mass first
yup, because before, i used a Vector3 Transform, so for a faster fall after i put this value
Or increasing JumpHeight a lot
Sorry, I meant FixedUpdate in that question. That's fine.
Serialize your JumpHeight and significantly increase the value
I don't know the suitable ratio, so you'll have to find it out yourself
Also it seems you're updating the IsJumping boolean. Are you sure the collision happens properly?
that work, thank
So Impulse requires a lot of force. Consider changing the JumpHeight as required in the Inspector and multiplying it by some value to keep it low
ok for example, i put 10 JumpHeight, and 100jumpForce to multiply each other
That's right
Additionally, I would like to suggest you to name your variables in camelCase, so jumpHeight and isJumping. Although, jumpHeight is not accurate, as this is not the height your character surpasses, so you may consider changing it to jumpForce
yup, i'Il do that
Sorry, wrong channel and person.
I have my own API and if there are bigger errors or execptions i want to start my own automated system that sends the needed Info to my API with their Account name, Machine Information, The Point where it crashed and the Stacktrace and not start the unity Execption / Problem thing.
How would ago disabling the Unity Error Popup / Window and replace it with my own code / access the Error stuff ?
Better said i want to replace the Unity Crash Handler thing with my own more hidden automated system.
I think this post pretty much answers your question:
https://forum.unity.com/threads/crash-log-entries-w-custom-logger.1051652/#post-6801728
that is complete bull
If you want to override the unity crash reporting system, you'll need the source code.
Another alternative is to maybe provide a launcher/wrapper app that would actually run your game and would detect when it exited with a crash. Then it could take the files that unity saved and upload them to wherever you want.
ive written crash handlers before
that is just a lazy excuse to "its hardcoded and we dont want to change it"

Well, it's probably in the C++ land. And they don't provide access to their C++ code for free
i will just make my own crashhandler and replace the one that unity puts into the project
so it starts my exe instead of the unity one
And it totally makes sense what they're saying. The game runtime could be messed up, so providing hooks for a crash reporter could mess up many things
Yeah, that's what I suggested
noone asking for hooks tho
just whatever data they are giving to the crash handler to be used by a custom exe
like my own exe
without needing to replace it each time
That's totally prossible though
thats super easy to do
but they want to sell their overpriced unity services crap so they make it harder then it needs to be
The info that the crash handler produces is stored somewhere on the user device and you can access it freely
It's just that you can't access it from the crashed app
since, well, it's crashed
and noone tells us where to look cuz
cuz i think having automated crash reporting to be send to their api for automated tracking with gh issues or youtrack is not only i would want
how did you find that
i was looking for that for 3 hours
google
unity crash report location
It comes with experience
im a gamedev for 8 years by now
but only hobby
never had the need to replace the crash handler with something automated
but thank you very very much
Is EventSystem.current.IsPointerOverGameObject() really supposed to hit BoxCollider ? 🤔 I have zero UI and it returns true for my floor which makes no sense to me...
I think it depends on the raycasters that you have in your scene.
If you have a physics raycaster, then yes.
I do on my camera yea..
Needed that for the IPointerEnterHandler etc to work. So how do you detect clicks on just UI then? 🤔
You shouldn't need the physics raycaster for ui.🤔
Unless your ui is not actually ui, but a physics object.
It's not UI, this is to detect clicks/enter for physics objects like floor tiles. I guess I need to exclude UI from the raycast I'm doing, so I guess just put all UI on a separate layer and use that to ignore it.
I don't get it. Does your ui have colliders??
Ah, okay, so you are using the event system both for normal ui on a canvas and for physics objects?
Is that right?
No, I don't have any UI at the moment. I'm doing void IPointerClickHandler.OnPointerClick(PointerEventData eventData) { ... some code here ... } for some gameobjects (non-UI).
Ok, I see.
I'd avoid relying on the events system for something like that, especially if you want more control.
Just a manual raycast from the camera is better?
The way I'm doing it is having a UI manager that can tell me if the pointer is over any of the UI(using that data for other stuff as well, like dragging and tooltips). While the player controller is handling interaction with the environment. It checks the UI manager for whether the pointer is over ui, before executing it's logic.
Yes.
And you can avoid casting it, when the pointer is over ui, to save some CPU cycles.
I've used a similar approach in the past but found it difficult to isolate code in smaller component scripts. All of a sudden my Door script for example will need to know about Player stuff (PlayerController for mouse input), and vice versa (since I need to check what I clicked in the PlayerController).
Maybe the PlayerController can use an interface, similar to how like IPointerClickHandler works, but for my custom raycast? So when I click something it's up to the Door to check in the implemented interface method if it was clicked:
class Door : MyCustomClickHandler {
// Wouldn't fire if clicking UI
MyCustomClickHandler.OnClick(GameObject clickedThing) {
if (clickedThing == gameObject) {
// do stuff when clicking on this door
}
}
}
This way I don't have to check in PlayerController what I clicked... Thoughts?
Sounds like just some design issues. Your door shouldn't need to know about the player or anything else that is not directly related to the door.
If you click on the door(or any other interactable object), you should probably handle that in your player controller and only call something like Close/Open on the door itself.
Yeah but if you then have many interactable objects you will end up with a lot of checks in the PlayerController which isn't really as scalable 😅
You don't have to end up like that.
One way you can do that is have the interactable objects implement an IInteractable or similar interface or an abstract class, that you can call Interact(this, someParam) on, and the object would handle the interaction.
What I have in my current project is a bit more complex. I have an actions queue system. I get the appropriate action from the interactible and queue it on the character controller. The action has access to the character, interactable and/or whatever else it might need and executes the specific logic.
How do I stop Visual Studio from correcting my own methods to Unity messages? Hard to escape too, because basically any input accepts the suggestion
typo wrong so the thing goes away, type the normal thing out
You can change how the auto complete works in the VS settings.
then delete the typo (if u add an extra character)
This is so stupid
Me: ...Quit()...
VS: Did you mean OnApplicationQuit()?
Me: No~
Vs: You did mean OnApplicationQuit().
normally i would let this be and then delete the OnApplication bit
btw is there a way to detect whether a button is pressed not through the editor but through script?
thank you
how does one detect button pressed without editor
the context is that its attached to a gameobject that keeps on making copies of itself and then destroys itself
thus the references would all be detached
Im not sure I understand your context, but you can use the Input class (https://docs.unity3d.com/ScriptReference/Input.html) if your using the default input system, or you can setup an action in a action map asset and bind to that through code, if your using the "new" input system
Hello again. I am suffering a problem with the ammo system for my weapons. Both the pistol and the bazooka uses the same GunDamage.cs but the pistol works flawlessly whilst the bazooka just reports "No Ammo" and that's it.
Here's all the code asscoiated:
GunDamage https://gdl.space/ejeqabivek.cs
GunController https://gdl.space/erugidoxaw.cpp
ProjectileManager https://gdl.space/urukuvixeh.cs
is there a way to open file explorer in runtime?
Have you tried googling it? https://forum.unity.com/threads/open-windows-file-explorer.371516/
I haven't
nope
Thanks for your help tho
I use this one @ashen pewter
https://assetstore.unity.com/packages/tools/gui/runtime-file-browser-113006
works very well
Yoo tysm
Thanks for the help guys
Hello guys, im new to this and Im following a tutorial, anyone knows why the squares (enemies) shows on the scene but not in game window? thanks
This isn't a code problem.
If the squares are being drawn by a "Screen Space - Overlay" canvas, then their position in the scene view doesn't correspond to where they'll appear on the screen.
Hey y'all
Trying to load AudioClips in parallel with async/await and MainThreading, but for some reason my audio clip always comes back null, no matter what happens? Looking into LoadSongFile() method specifically. It always comes back as null in the debug.log. Stuck for a few hours, i'm embarrased to say, but I'm new to working with parrallel threading so i have no idea what's wrong. This only happens when using the ThreadDispatcher though, i justadded it on because I can't create things on anything but the Main Thread.
Here's the relevant scripts:
Initializer.cs (with LoadSongFile()): https://pastebin.com/MKAFcMaj
UnityMainThreadDispatcher.cs (Relevant to RunOnMainThread() method): https://hatebin.com/zbmiuwevnm
if you need more info let me know i'm just gonna go eat really quick
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.
Your hastebin link is broken
Also async await are not generally related to multi threading in Unity
my bad
replaced it with a pastebin
i mean like tasks or something like that
Hello! I'm trying to add unity ads to my game. In unity editor, when I click the button that's supposed to show ads, it says everything works. But when I build and test in my phone, it doesn't show anything
yeah wish everyone did not see async and await and immediately think threads. its just a method for dealing with concurrency how that is implemented has nothing to do with Tasks
i have watched the entire “Beginner Scripting Tutorial” series made by the official unity yt channel, and i was wondering if you guys think i would be able to make my first project using the knowledge i have acquired and some stuff from the unity forums
nobody here can possibly know if you've properly absorbed the knowledge that was presented. so the only objective answer to your question is "try it"
hmmmmm, yes i didn’t think about that kind sir. i shall try my best
Go for it. You will never stop needing to learn, so may as well test yourself periodically
Don't be afraid to do bad work and restart. That is a HUGE piece of learning.
got it 👍 thank for that peice of advice
thanks
Hey so I've been optimizing my game recently as when using the profiler I noticed my garbage collection would spike pretty frequently. I start with learning a little more about the better practices of memory usage. I noticed that one of the big ones was creating new instances in code that is repetitive. I can understand that for expensive operations such as creating gameobjects, but what about values such as vectors? Would you recommend that I initialize a temporary vector and reuse that one rather than creating a new vector every time? Or is the difference negligible.
vectors are value types so if you are creating new instances of them inside of methods they will live on the stack and won't have any impact on GC
GC impact will come from instantiating reference types, or anything that lives on the heap that you only use for a short time
You can easily see what is being allocated by frame with the profiler.
Find the worst offender.
Alright got it! Thank you ^^
Is there anyone here who has experience with movement on orbiting objects, or anything similar*?
Many people, just ask your question. No one wants to make an effort to initiate helping someone else
that question is also very vague, since orbiting objects could be a physics simulation or just parenting stuff to other stuff
Are we talking about just something circling something or like, actual orbital mechanics via forces/gravity?
how can i instantiate prefabs but create an instance of its materials since i need each material to be different in a few of its properties on a per object basis
when you access the material or materials properties of Renderer, the materials areinstantiated
so that happens automatically
wouldnt that just be the reference to the material ...
that all the prefabs reference
unless you are saying if i do:
var mat = renderer.material;
//change the color property
that will now only affect that specific game object's material not all other instances?
ah i see.
I’m trying to get my player to flip when I move the other direction. The sprite renderer is saying it slips on the x axis but is not showing in game. Is this code or something to do with my sprite
Like, actual orbital mechanics, and the reason I asked if there were anyone with experience, is because it's not a specific problem, or error.
What way are you flipping it, like rotation, scale, flipping the sprite?
Using the UI Toolkit with custom uss vars, is it possible to edit vars in the UI?
Eg I have something similar to bootstrap in a vars.uss file:
:root {
--brand-primary: #375a7f;
--brand-success: #00bc8c;
--brand-info: #3498DB;
--brand-warning: #F39C12;
--brand-danger: #E74C3C;
}
I'd like to be able to edit these in the UI Builder interface, can I? Or possibly connect them to a scriptable object if not?
Got it
Well what do you intend to ask?
How I would stick the player to the planet, I've tried matching the velocity, parenting the player to the planet, and a couple other things I don't remember.
Well, what makes you stick to the planet earth?
I already tried simulating gravity.
You really think I'm an idiot?
No. He asked you a question needed to solve your own question
And? It didn't work?
Apart from the floating origin problem of space simulations, you'll need to simulate your own gravity
so you apparently didn't do it right.
no need to get hostile for no reason.
Am I here asking questions?
How did you try to implement gravity
I did.
can I see
physx has it's own gravity system that you'll need to disable
so that you can implement your own.
Hello. Would anyone be willing to help me figure out what I'm doing for my code? (I know what I'm trying to do but I cant actually figure out how to achieve that)
If you really need help, you need to be able to provide enough information to us. And with an attitude like that, you're not gonna get much help.
I disabled gravity for all physics objects, do I need to disable a physics setting?
https://dontasktoask.com/
just ask the question, look at the #854851968446365696 on how to if you arent sure
Okay.
that's probably enough. can you paste your gravity implementation?
And you still didn't answer my questions. But I'd assume that the answer is that it didn't work.
In that case, did you figure out why?
The name isn't extremely informative, but:
{
Vector3 gravityUp = (transform.position - referenceBody.Position).normalized;
Vector3 localUp = transform.transform.up;
Quaternion targetRotation = Quaternion.FromToRotation(localUp, gravityUp) * transform.rotation;
//Debug.Log(gravityUp);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 50f * Time.deltaTime);
moveDirection = new Vector3(moveAction.ReadValue<Vector2>().x, 0, moveAction.ReadValue<Vector2>().y).normalized;
if (!IsGrounded())
rb.AddForce(-transform.up * referenceBody.mass, ForceMode.Force);
}```
three ` for a better code paste btw
And how did you apply the movement to your character?
I personally would've just used gravityUp in my addforce call
Changing the rigidbody's velocity.
Changing the velocity overrides any forces applied to an object. So there's your answer.
I tried that, then tried this, and forgot to change it.
I know.
what doesn't work?
I don't have to move to get launched off the planet.
Then there must be an issue in your calculation somewhere. Did you try debugging the relevant values?
the big issue is that you don't have a realistic gravity calculation
if you jump, the jump is gonna be massive
earth's gravity is 9.82M/s^2
and that does a good job of keeping everything grounded
}```
at least I think that should be right
your rotation code might also be getting you lodged inside the collider and shooting you up
I have no idea how you could possibly have read that from what they said. Please don't speak to people like that. Dlich is trying to get information in order to help you. We have no idea what stage of knowledge people are at. I do not appreciate you calling people that don't know stuff like that idiots.
So, I'm trying to make a dynamic music system. I currently have my music being held in a audioQueue list. I'm what I'm attempting to achieve is:
- Have my music play, one clip after another. (1, 2, 3, 4...)
- Have a fall back once the music clips played reach a specific song. This will repeat the current song playing if its position in the queue is the same as the measure where it should stop. This is defined in
inputMusic.Measure. The songs playing would look something like this: (1, 2, 3, 3, 3, 3). - If the
inputMusic.Measurevariable is changed, it should finish playing that song, and then continue to play the songs with the pattern mentioned previously until it reaches the next instance ofinputMusic.Measure.
(I apologize for the poor description. Please ask questions and I will clarify if you are confused)
Currently, I am able to run this code and it nearly functions as intended. The audio clips play as follows: (0, 1, 2, 3, 2, 2, 2...) My issue: When it is supposed to loop on the 3rd clip, it returns back to the second clip instead. Any help or input would be appreciated, as well as any input on how I can improve.
Here is my code:
https://pastebin.com/Az1Vj3T7
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.
Okay.
@rain tidejust an fyi, if you're planning on having multiple planets, or any 3d space game at all, you will need floating origin or something similar. otherwise you will exceed the limitations of 32 bit floating point numbers and everything will start glitching out past a certain point in space.
You may want to tell folks what those issues are.
Yeah that may be a good idea...
Alright, thanks for the reminder.
I edited it describing my issues
Hi I’m still having this problem please help 🥺
The problem seems to be that I'm going through the planet.
remove that rotation code temporarily and see if things get any more stable
you also said that you're moving your player with velocity. that is also a likely culprit
How would you want me to move in a way that would work?
I don't know. Moving a player around a circular planet is a lot more difficult to get right than moving a player on a universally flat ground
I have no clue what that video is supposed to show
if you're trying to move your planets like they'd move in our real universe, I would probably not do that.
Sorry, I'm not moving with velocity, I'm using the MovePlayer method.
That's the point.
idk what a moveplayer method is
and second, you're going to run into floating point issues like I said earlier, very quickly
and you don't even have a system to handle that yet
MovePosition, wow sorry.
MovePosition bypasses the physics engine
which is probably why you're teleporting through the planet
Oh.
after you fix that, you should let your simulation run for a few minutes and see how glitchy everything gets as your planets move past the 10,000+ meter mark. so you can see what I'm referring to w/ floating origin
you should really consider just having statically oriented planets, like most major games do. nobodies really gonna know the difference anyways...
As an update, I found out my issue is the fact that I limit the running of my code if it passes an if statement:
if (clipsPlaying.Count < 1)
What can I do to work around this or even what can I redo to make this function without removing things from my audioQueue? This line of code is important to making sure multiple clips dont play at once unless intended to, however I dont know what I can do to fix this...
Does anyone have any ideas?
So if I create submeshes for a mesh, is there any way for me to feed it different sets of vertices for both or do they have to share the same set of vertices? Because I'm only seeing a way to do this for the triangles
there's only one set of vertices
the triangles for the submeshes reference from the same set of vertices
So how does a mesh know theres a submesh?
What do you mean by it "knowing" there's a submesh?
Maybe you're asking about this? https://docs.unity3d.com/ScriptReference/Mesh-subMeshCount.html
why's my python code is error in unity
it works pretty well in vscode
This looks like a runtime error. Something about unicodeescape codec? Not sure what that codec is for.
its actually because i dont add r before the string
yea it was a dumb moment
Hey. When having a MonoBehaviour A and its derived class, B, both with the Awake method, is it possible to give A.Awake the functionality, which will also execute when B.Awake is implemented, without marking them as virtual and override?
This way, I don't want to always call base.Awake()
No. You have to call base methods in the override if you want them to execute
Alright, it seems so. Thank you
is python can be used in runtime?
No. At least not by default.
You could probably use the OS api to launch a batch file or a python script, but that would require python to be installed on the user machine among other things.
Hi all, is there a way to enable word wrap in the Unity console?
For UGUI InputField, it seems like selectionAnchorPosition and selectionFocusPosition reset to 0 when you lose focus. Are there properties that track the last known positions, or do we just have to do our own tracking on top of it?
My use case is that I have some buttons that essentially pastes some predefined texts and I'd like it to replace the selection.
Hi, I want to get access of the username of a player in the server side; which is stored in the cloud save: player data but to get access I need to log in with an admin account, I tested the ServiceAccount but there is no documentation about how to connect to the service account. I tested this method: ServerAuthenticationService.Instance.SignInWithServiceAccountAsync(); but I have this error: ServerAuthenticationException: HTTP/1.1 400 Bad Request
hii, im having a problem with my players animation when they move. it works in the editor perfectly and no errors show up in the log. but when i build it the animation is stuck on idle instead of switching the walk anim like in the editor. does anyone know how to fix this?
what build target?
development build?
have you checked the player log ?
just this one
is there anything here that looks like it could be wrong? sorry i dont know alot about this part
To start with this is not a code question But...
Select development build. Build and Run then check the player.log for errors.
The !log location can be found in the documentation
!logs
ty ill give it a try
im new to the server so i wasnt sure what chat to ask in, since i also dunno whats wrong so 😅
for future reference if in doubt #🔎┃find-a-channel and #💻┃unity-talk
tysm
its just in the console in the editor that should tell me if something is wrong after the build right?
No, when you Build and Run any errors will be written to the Player log, which is why I told you to look at it
sorry where can i find the player log`?
did you not read this?
#archived-code-general message
i didnt see that earlier
Hello. Is there a more efficient way to get the current playing time of an audio clip instead of AudioSource.timeSamples / AudioSource.clip.frequency? Thanks
AudioSource.time
hey im trying resize my rendertexture however the camera refuses to render to the texture until i enable and disable the camera script in the editor is this a bug?
the camera has the render texture it just refuses to render unless i turn the camera script off and on
Anybody know how can I make my character hold the weapon with 2 arms. I thought about adding a public gameobject to a script which is on the both lower arms but didnt know what to do next. I also want to use those slots because I want to also use one handed weapons
I want to use slots too because there are another actions character does when weapon in not 2 handed
Maybe animation rigging, look into unity's package for that.
Depends on how you want these objects to move
If I want to create a turn based combat with animations, would creating coroutine within a coroutine be a good idea?
Top level coroutine as a "loop" for each character
Then each character would have its own coroutine to play its animation.
Is that correct way?
Tbh I could also just have infinite loop and reset index when I reach last element until specific condion is true(i.e. enemy or player lost)
This would only have coroutine for animations right?
A coroutine is just a way of running logic after some time, so this is incredibly vague especially as to why you need these. Or what a "top level coroutine" even is since it sounds like you could just run logic in update.
If you're creating a ton of coroutines, it wont be great and also controlling the flow of when things happen exactly may be a pain
I see, I am working on a prototype so I might get a better idea of what I need once I start writing combat logic.
It's meant to be automated combat, so it loops through all characters and they do their attacks/animate etc.
my logic would be:
void Update()
{
StartCoroutine(CombatTurn);
}
IEnumerator void CombatTurn()
{
foreach(Unit unit in units)
{
yield return unit.DoAnimate();//I assume its another coroutine? It has to wait until this character stops animating
}
yield return null;
}
This could be wrong, but that's current idea.
Starting in Update is your first mistake
Yeah thats true, I just saw it in an example somewhere, it will start only 1 time, since whole combat is automated from start to finish.
it's really just a bunch of things animating, but it has logic for combat too.
Loop units -> unit.DoLogic() -> unit.DoAnimate()
Maybe do some experimenting with coroutines first to see how things even run. Like that yield return null at the end does nothing too
Yeah I will do that first, the project is still empty lol
I thought that you always need to yield return null to stop the coroutine
but maybe its used to end it early
But still I'd just try to define as much as I can in update and have my own control of when things are running. Maybe with some pseudo state machine though im not sure what logic you intend on actually running
No, not at all. Instead of just guessing based on examples, look at the docs and learn it for real.
I kinda want to take advantage of coroutines, just to learn them a bit.
But the logic is simple, some calculations for combat + animating simple 2d sprite.
I will be back in an hour or two if I get closer to writing some code, I should have a better idea by then!
https://hatebin.com/jfngrqiyyv I have these script to move left upper , right upper and low arms but I want to be able to move lower arms only when weapon isnt 2 handed.
This definitely should be in #💻┃code-beginner given that code. You could store if the weapon was 2h or not on the weapon itself, but I dont know enough about what you're actually trying to do here. This logic looks.. fragile to say the least
I have an issue with async tasks cancelling. I’m creating a simple game creation scene where you can change between game modes. There is local, host and join and some of them fetch data from the Relay server or Authentication Service.
When the user selects host game mode it starts fetching some data and after it finishes the data is displayed on the screen. But if in the mean time the mode is changed then it still shows the previously fetched data on the current freshly selected game mode screen.
I would like to cancel these tasks when the other mode is selected, but was wandering how? Is CancellationToken the right way to go about it? Tried to implement it, but had some issues.
private async void OnGameModeDataSelected(ISelectable selectable)
{
GameModeData gameModeData = selectable as GameModeData;
#if UNITY_WEBGL || UNITY_EDITOR
await HandleRegions(); //fetch data from the Relay
return;
#endif
}
//example method
private async Task<bool> HandleRegions()
{
try
{
foreach (var region in await RelayManager.Instance.TryToListRegionsAsync())
//stuff happening here
}
catch (Exception e)
{
HandleErrorText(e);
return false;
}
return true;
}
The TryAddTile method adds a Tile to the Tilemap on the specified position, if it's available.
When recording the changes and setting both player and its Tilemap dirty, the torso seems to be collapsed after undoing the changes.
Undo.RecordObjects(new Object[] { _player, _player.torsoTilemap }, "Paint torso");
if (_player.TryAddTile((Vector2Int)position))
{
EditorUtility.SetDirty(_player);
EditorUtility.SetDirty(_player.torsoTilemap);
}
My question is, what am I doing wrong that the Tilemap does not get saved?
When I make a development build I get a lot (>50) of errors like these:
The referenced script on this Behaviour (Game Object 'Player') is missing! A scripted object (probably Players.Player?) has a different serialization layout when loading. (Read 32 bytes but expected 88 bytes) Did you #ifdef UNITY_EDITOR a section of your serialized properties in any of your scripts?
However, I don't use #if UNITY_EDITOR or any other #ifs anywhere, aside from a package I'm using. I've Googled around a bunch, but none of the answers are helpful. Most give solutions like "I copy pasted every script and now the error is gone" or they do actually use #ifs. Since the errors are shown on basically all of my scripts, I'm kind of at a loss where to start. Any help is hugely appreciated!
Here is a complete log output: https://docs.google.com/document/d/1hXmh1SlaFanRyubuLlryTnsbV_KdUs8KRNH0WTtpV2Q/edit?usp=sharing
And Player.cs code: https://hatebin.com/ajkyrmdcsk
I've made a simple scene with only an object and a movement script, and it still gives me the error. I've tried removing things until I don't get the error anymore and apparently the thing throwing the error is... All my variables???
My methods are fine, but as long as I have any public or [SerializeField] private variable in my script I get build errors. I've tried it with public vars, private vars and [SerializeField] private classes, enums, floats and ints. Only private vars don't give errors. All methods are fine.
So now I'm wondering... What the heck's wrong?
Here's the script: https://hatebin.com/hliqdrrqvq
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SheepManager : MonoBehaviour
{
public PlayerData playerData;
public GameObject sheep;
public Transform spawnPoint;
public GameManager gameManager;
public int spawnedSheep;
private void SpawnSheep()
{
if (spawnedSheep <= playerData.sheepAmount)
{
Instantiate(sheep, spawnPoint.position, Quaternion.identity);
spawnedSheep++;
}
}
private IEnumerator SpawnSheepRoutine()
{
while (spawnedSheep <= playerData.sheepAmount)
{
yield return new WaitForSeconds(1);
SpawnSheep();
}
}
private void Start()
{
StartCoroutine(SpawnSheepRoutine());
}
}
why only 1 sheep spawn on start
First of all, you check if (spawnedSheep <= playerData.sheepAmount) twice. I recommend removing the check in SpawnSheep()
Second, it's a bit hard to say without more info. What number is playerData.sheepAmount?
And maybe multiple sheep are spawned, but they all get spawned on the same point so they overlap?
because playerData.sheepAmount is zero
if i put amount in script its working but in saved json file they dont work
but if i debug.log(playerdata.sheepamount) it show right number
I'm making a rhythm game and I need to spawn the notes at a certain time in milliseconds. This is how im currently doing it:
public class SpawnNotes : MonoBehaviour
{
[SerializeField] BeatmapParser beatmapParser;
[SerializeField] AudioSource song;
public long ms;
private Stopwatch stopwatch = new Stopwatch();
public int currentNote = 1;
private bool songStarted = false;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
ms = Convert.ToInt32(stopwatch.ElapsedMilliseconds);
if (songStarted && Convert.ToInt32(stopwatch.ElapsedMilliseconds) == Convert.ToInt32(beatmapParser.notes[currentNote].Item2))
{
UnityEngine.Debug.Log("Spawned Note");
currentNote++;
}
}
public void StartSong()
{
songStarted = true;
stopwatch.Start();
UnityEngine.Debug.Log("ran");
}
}```
However, the if statement is never fired. I'm assuming this is because the update method is tied to the frames and cant keep up with exact ms. Is there a better way I could do this?
The StartSong() function is being called in a different script btw, the issue isnt that thats not being fired
Yeah but it goes straight past the time its meant to fire at without firing. I know my method is probably flawed so im asking for a better solution for my case
You should check if it is greater or equal to, not if it is EXACTLY equal to.
Hey! Is anyone else struggling with IHeartGameDev procedural environment animations?
I started the unity tutorials a couple of days ago and Im having trouble building everything from scratch.
The guy explains things really good and the editing is fantastic, but there is some stuff, mostly components attached to the GameObjects, that he has done outside the video and are never shown, for example:
-Rigidbody
-Capsule collider
-Animator
-PlayerStateMachine script
Sometimes also there are scripts that change between videos without context or explanation.
Since the guy is widely known in the community, I was wondering if someone also had this same problem and managed to solve it and get the thing to work.
If someone had already the finished proyect, or the parts Im missing, Id be extra satisfied! But I'll settle for a little help.
Obviosly Im willing to share the code I got if needed, just ask!
For help you should share what you're specifically struggling with. It's unlikely anyone that's also doing the course is going to see this, remember it, and help you.
For something like this maybe you'll want to find if they have some discord server or place to talk related to their videos
They do have a discord server, but its attached to a patreon, and Im a broke ass dude. 💀
That kinda thing is a frequent problem with tutorials, but hard to bugfix without going through it. Especially if they just leave stuff out.
Yeah, but idk, since is a big channel I am expecting, with a bit of luck, to find someone that aldeady went throug it and could help me.
Made a post in reddit too
Then not much can really be said, since you also havent really asked a question. YouTube tutorials generally are shit so maybe dont just try copying an exact 1 to 1 setup. You can make your own solutions if you've learned enough from it
My problem is that there is stuff missing, the question is if someone figured it out.
Sadly, cant make my own solution tho, if I dont know how that missing part works.
;(
3 of the 4 components you listed are built in unity components if you arent aware
I know, but I am not aware of their config
Made a copy to test stuff but couldnt get the errors fixed, those evil red messages are always there.
As I said above, dont try copying an exact 1 to 1 setup. You should first learn to code
It seems like you're just blindly following a tutorial. Honestly theres almost nothing you need to do to setup a rb or collider. It's all unique to your game anyways so those should be things you're setting up different from the tutorial
Well, lets say the collider and the rigidbody are not the problems, still missing a script, animator and such stuff.
Im trying to understad things, not blindly following, but im aware that I couldnt do it alone since is over my level. I dont have that much expecience using Unity.
My target is to get it to work, then modify it to fit my needs.
Hey guys what is your opinion about muse?
is OrionEditor something you made or is it an asset?
okay then #↕️┃editor-extensions and yes, show code
but the error is pretty clear, you did not call BeginLayoutGroup but you are trying to call EndLayoutGroup
` public override void OnInspectorGUI()
{
DrawDefaultInspector();
OrionFile f = (OrionFile)target;
if (GUILayout.Button("Create new Animation"))
{
Save(f);
}
GUILayout.BeginHorizontal();
if (GUILayout.Button("Save Animation"))
{
if(f.GetOrion() != null)
{
f.Save(f.GetOrion());
}
}
if(GUILayout.Button("Load Animation"))
{
string path = EditorUtility.OpenFilePanel("Load animation", "", "orn");
Debug.Log(path);
if (path.Length != 0)
{
f.Load(path);
}
}
GUILayout.EndHorizontal();
GUILayout.BeginVertical();
if (GUILayout.Button("Reset Animation"))
{
if(f.GetOrion() != null)
{
f.GetOrion().ClearLayers();
}
}
GUILayout.EndVertical();
}
public void Save(OrionFile or)
{
string path = EditorUtility.SaveFilePanel("Save animation", "", or.name, "orn");
Debug.Log(path);
if (path.Length != 0)
{
or.Save(path);
}`
the error becomes from here
it tells you exactly whats wrong and how to fix it, whats the problem ?
i dont know, i dont find the method BegingLayourGroup
maybe its related to this
https://forum.unity.com/threads/endlayoutgroup-beginlayoutgroup-must-be-called-first.523209/
I have a custom editor that appends a button to the default inspector for a ScriptableObject sub-class. When this button is pressed, I run my build....
Im making an ar app, i made an animation in unity using blend shapes imported from Blender, when I enable the objects with blend shapes, my application crashes, when i disable these objects it works fine. do blendshape not work on mobile? struggling to find anything online
Use the android logcat to see the logs. There should be some info about the crash
hey guys is there a way to force unity to regenerate csproj and solution files
i figured it would regenerate them when i launch the scene but nope
delete them
they are gone
Assets->Open C# project
is the external edtior setup right
how it generates them depends on the target ide
like Rider, VS and VS Code all have slightly differnet files for it
and whats the error
thats pretty strange
i had this on my laptop and threw it on git and pulled it onto my desktop
so maybe i missed a file on the laptop
but idk what
nah pretty much everyone ignores csproj files in git
yeah i didn't commit anything that the gitignore has by default
since they're all generated files
well defualt gitignore is no good for unity
there are alot of things you will want ignored
i used the one that github supplies i think
can i delete library or something to force a full rebuild
would start with this as a base
https://github.com/github/gitignore/blob/main/Unity.gitignore
yea thats whaty i have
got the package for it installed in package manager
oh ffs
that's prob the issue
i had problems with other missing packages
must have not committed that file
yeah pretty much all ide support is in the package
exists a way to fuse diferent sprites in an animation
i have some sprites but i dont know how to fuse then
Wdym by "fuse"?
like layers, but with booleans
is a menu
i dont really how could explain clearly but i wanna reproduce a diferent layers in a animation in a specific moments
like in this sprite
Do you have some example of how you want it to look like?
Also, is that really a coding question?
This is either a color filling or an overlapping sprite with a mask.
A simple script with an ui image would do it. You can control the fill with the fillAmount property of the image.
anyone have any advice on how to make a custom animator event system? unity's system is utterly unusable and I can't really find any good alternatives except making one myself
Maybe if you describe what issues you have with unity's animation events, and what you want yours to do, the answer would be a bit more helpful
events do not register consistently
so the whole system becomes useless for anything beyond maybe some visuals/sound
Huh. I have never experienced that. That would indeed make it tough
well I have, a lot
which meant I had to stop using them, and I haven't found a good alternative that doesn't cost $90
the problem with the existing one is that if a frame in the animation is skipped due to changes in the animation's speed or low FPS (which happens a lot), the event tied to that frame never gets called
so for my system I want to tie events to coroutines which are guaranteed to be called properly
but I have no idea how to make an actual editor for it
I don't think that's how it works. It should be calling the events between the previous and current sample. It would barely work at all if skipping frames would prevent it from dispatching events.
well I don't know exactly what causes it, but that's not really the point
the point is that it doesn't work
Perhaps with a little troubleshooting you could get it to work as you expect, instead of reinventing the wheel.
I've looked a lot on the forums and the prevailing answer is usually "the unity devs don't even know why it doesn't work"
and I don't feel like spending another 2 years trying to use this system that breaks at seemingly random times
also I've noticed that if you have transitions at the end of animations, the events during the transition often aren't fired
but even without transitions it's inconsistent
Well, we can't really help you if you don't have a specific problem. That being said, if your system is dependent on the animator, it would probably have similar issues. So you might need to implement a whole new animation system along with it.
? I don't understand what you mean
I asked for suggestions for how to implement my own system, specifically making an editor for it
and I don't think I would need to implement a whole new animation system
this system would be animator independent
The question reaction is for that spam message that seemingly comes from you? I'm not sure. Am I the only one who sees that?
Ah, I thought you said an animation event system. I didn't see you say anywhere it would be a whole new animation system entirely
from me? what lmao
it was from a bot that is now banned
It is in all the channels
Ah ok, guess my discord bugged out. Sorry
you can see it says "today at 11:56 AM" meaning it was a message from someone else
Well, how are you gonna know what animation frame it is then?
by keeping track of the timings in coroutines
all I really need is to know how far into the animation the event should be, and the playback speed
I don't see the issue with that?
You're making an assumption that the animator would update at the same rate. Transitions and what not might be affecting it.
but that doesn't matter, I just need the timings to be correct
if it doesn't line up frame perfect that's fine
as long as the timings are right and the events actually get fired, I'm good
the visuals come second to functionality
which is not how the built-in animator system seems to work
Okay.
As for about the editor side, you should probably ask in the #↕️┃editor-extensions
As well as check the manual/API docs.
It is for me 🤷♂️
I have literally never had an event get skipped or heard of it happening
well you're lucky then, but that doesn't really help my issue lol
you got it
That would imply that what you need is not really an animation event, but some kind of sequencing system.
as for hearing of it happening, just google "unity animation event not firing"
I don't think it's luck. I think it is misattribution of the problem
But either way, best of luck
Animation events are intrinsically tied to the visuals.
alright, whatever you want to call it
if you have any suggestions on what I might be doing wrong that would be very helpful
I may be exaggerating how often this happens, but it's common enough that it makes gameplay inconsistent and unfair which is something I want to avoid at all costs
and on second thought I don't really need to make a proper editor extension (at least not yet)
For that you'll need to debug it properly and provide us with more information.
But my guess is that the issue is on transitions and/or blending of animations, which is not impossible depending on your animation states setup.
If you have a fighting game of sorts, and depend on the events for hit/dodge or other mechanic timings, then it would definitely be unreliable
I'm making an rpg and in the beginning I was using these events as an easy way to make complex weapon behavior without having to write a bunch of custom scripts
I thought I could fix the issues I had previously had with animation events, but I couldn't
I guess that makes me bad at debugging or whatever
but anyway, I'm gonna get to work on this (even though it's already 5am)
Umity animation events aren't great.
Hi, have a nice day.
I'd like to ask, what possibility make a scene too slow to load? I have a simple scene like this, with some vfx and textures around 200KB. I checked the profiler but nothing-suspicious. I use LoadSceneAsync and It took about 9 seconds to load the scene.
What do you see in the profiler?
You could try building only that scene and looking at the build report for what takes how much space. This could provide some clues as to what makes it long to load.
When I make a build of my project I get a bunch of errors on public & [SerializeField] private variables. For some reason private variables are fine. They don't show up when in the editor, only when I run a made build. Does anyone know why this might be the case?
The errors are the following:
The referenced script (Unknown) on this Behaviour is missing! The referenced script on this Behaviour (Game Object '<null>') is missing! A scripted object (probably Animations.AnimationSequence?) has a different serialization layout when loading. (Read 44 bytes but expected 296 bytes) Did you #ifdef UNITY_EDITOR a section of your serialized properties in any of your scripts?
And again, this doesn't happen if I comment out all public & SerializeField private variables. Very strange.
Share the code in question and details of the errors.
https://hatebin.com/hliqdrrqvq this is the class in question. Everything that throws an error is commented out. The other referenced classes, Animatable and CharacterMover, don't have any public or serialized variables and don't throw errors
The entire error is:
`Begin MonoManager ReloadAssembly
- Loaded All Assemblies, in 2.611 seconds
- Finished resetting the current domain, in 0.002 seconds
<RI> Initializing input.
New input system (experimental) initialized
Using Windows.Gaming.Input
<RI> Input initialized.
<RI> Initialized touch support.
The referenced script (Unknown) on this Behaviour is missing!
The referenced script (Unknown) on this Behaviour is missing!
The referenced script on this Behaviour (Game Object 'Square') is missing!
The referenced script on this Behaviour (Game Object 'Square') is missing!
A scripted object (probably Movement.TargetMover?) has a different serialization layout when loading. (Read 32 bytes but expected 36 bytes)
Did you #ifdef UNITY_EDITOR a section of your serialized properties in any of your scripts?
UnloadTime: 8.304700 ms`
this is a Windows or Mobile build?
Windows
I've made sure that I don't have any #ifdefs in my code, and my Test assemblies are set to build in Editor only
My guess is you have a problem with your input action maps for the input system as this is scriptable object based
Ooh I see, haven't looked for any issues there yet
this
<RI> Initialized touch support.The referenced script (Unknown) on this Behaviour is missing!
and this
A scripted object
point towards that
Oh, my bad, there should be a breakline between those two lines. It's
`<RI> Initialized touch support.
The referenced script (Unknown) on this Behaviour is missing!`
Regardless, I'll have a look at my input settings
you may find just regenerating your input actions solve the problem
Also make sure you are using the latest input system package version
I've got 1.7.0. I see that there's a 1.8.0 online, but the Package Manager doesn't show an update button. Should I remove 1.7.0 and try to install it again?
what Unity version?
I'm on Unity 2022.3.21f1
then 1.7 is the best you get
Alright, thanks!
if the worst comes to the worst I would update to the latest 2022.3 version
I've tried updating to 2022.3.4f1 to fix the issue earlier, but that didn't fix it sadly enough
.21 -> .4 ?
Yes
how is that an upgrade?
Oh my bad, the other way around! I used to be on .4, and then I upgraded to .21.
I need a coffee 😓
the latest 2022.3 is .38
I didn't yet have any Input Actions, so I made a new asset and generated a C# file for it, but I still get the same error. I'll try upgrading to .38, and I'll see whether Input Actions 1.8.x is available for that version
? How are you using the new input system without input actions?
I'm not sure honestly, I set this all up at the beginning of the project (>6 months ago), and that was my first time doing so, so it's a bit hazy now
I hate to say this but that sounds very much like the root of your problems
Yeah I think so too
I'll go do a deep dive into correctly setting up the Input Actions, and I'll see if that fixes the problems
Regardless, thanks a lot for pointing me in this direction. I would never have thought of looking here myself
I guess you have never looked at the actual input system code, it is very brittle and fragile if not used exactly how Unity wants you to use it
For the new IS or the old one?
new IS
That sounds... fun
I took one look at it and just built my own input system based on the low level code. Not fun but at least it works
I just checked my Input System settings, it was on "Both"
Just switched it to the new system and I'll incorporate it according to the official docs
How can I get the pressed keyboard key? I found online this solution, but it seems inefficient to loop through all the possible key codes. Are there some input events I can listen to make it better?
Heres the example solution:
void Update()
{
foreach (KeyCode keyCode in System.Enum.GetValues(typeof(KeyCode)))
if (Input.GetKeyDown(keyCode))
Debug.Log("Key Pressed: " + keyCode);
}
I’m trying to avoid the new input system, because my project is generally mouse only and using it to detect a left button click seems like an overkill
Howdy. I have a problem.
So I have a value 0..1, and I want to check if it multiplied by 10 is a multiple of 2 (so 0.2, 0.4, etc.). But the native % operator returns stuff like 1,192093E-06 for 1.0 (10). What do I do?
Cache this
KeyCode keyCode in System.Enum.GetValues(typeof(KeyCode)
for the rest it's your only option using the old input system
you can check if its approximately 0, which is what that number is anyways
hiw
how
https://docs.unity3d.com/ScriptReference/Mathf.Approximately.html
or make your own comparision for it
for future reference try to spend at least 30 seconds understanding what you have been told before responding 'how'
i know what i have been told, idk how to do that
Alright, thanks
A google of 'Unity approximately' would have led you to the documentation
it is also in the #854851968446365696
Dont
Respond with new issues you have not researched.
strange question but how would i go about implenting a battle system for my game? not the technical way; i want to learn HOW to make it. i have the knowledge i need but im kind of stumped. was thinking of using enums for state machines, lmk if thats a good idea
and scriptable objects for the enemies and their stats
What kind of battle system?
turn based
similiar to undertale but with a twist
heres a diagram i drew
Not sure what to start from. Surely, you will need an abstract class Enemy to then derive specific enemies from it
yeah i already did thta
What's next?
i just want to make it perfectly, and not have to restart it because of sphagetti code, so im trying to come up with a plan
i guess a combat manager with a state machine
and scriptable objects for enemies
Well, you definitely need a PlayerController script for your player. The game can be managed by the GameManager Singleton, which contains all the required states and methods
combat manager would be more organized
i already have that set up
Sure, you would also need a UIManager to update things associated with the UI
why cant it just be in the combat manager and just handle all the combat ui there?
because i already have different singletons like dialogue manager and inventory manager so i would have to rearrange EVERYTHING
seems like a hassle
Combat manager only manages the dialogues? Then that's fine
If you have a Singleton for every part of your game, it's fine
yeah thats how i approached it
Does Managers have DDOL on it?
whats a DDOL?
Don't Destroy On Load
i dont know how to implement that
is it DontDestroyOnLoad(transform.gameObject);
in the awake function?
I'm having troubles with my gun not shooting the asteroids It might take a while but some help would be appreciated! here's what it looks like.
providing more context would help
Yeah for sure! I'm trying to have it so that the gun will always shoot the asteroids but depending on the angle or distance sometimes it will just keep missing target and I was hoping some fresh Ideas on how to fix that since I've ran out.
You have said you have different Singletons. They usually go with DDOL and are persistent on scene change
i added the DDOL now, thanks for telling me
Not sure whether it's going to work properly if you have simply added [this line](#archived-code-general message) to your code
i put it into an awake function
Consider creating a [generic Singleton](#archived-code-general message) and deriving the suitable Managers from it
seems unnecessary to be honest
but still nice
Seems much more necessary for you than repeatedly creating the same code, which, in your case, won't work
true i guess
does anyone know why rigibody.AddForce() is inconsistant with screen resolution? and how can i fix this?
You'll have to show the code
I'm sorry but I have absolutely no clue what you mean by that
I don't know where to put this so will ask here in case someone can help.
Has anyone come across this and knows a fix for it?
Unity V 2022.3.11
Deleting the folders from the Unity Editor data folder does nothing and I have no idea why this is happening 😅
Any help is greatly appreciated!
The amount of force applied doesn't change based on the size of the screen . . .
when i maximize the game tab
it applies different force
you have duplicate scripts in your project
I'm assuming they mean different framerates which changes when resizing the game
could be
In a coroutine, how do I start another coroutine and wait for it to finish?
so anyways how do i get consistant force with different screen sizes
yield return StartCoroutine(mymethod());
no code, no way we know what's going on
Continuous force needs to be applied in FixedUpdate, not Update
so that waits until the coroutine ends and resumes the parent coroutine
ohh that makes sense
let me try that and let u know if it works
would I have posted it if did not answer your question?
but like im curios
just making sure
when it is related to physics, put it in fixedupdate
fixedupdate runs every physics update instead of frame update
so it is independent of frame rate
yea i knew that but i didnt think rigidbody.addforce is physics
see Fixed Timestamp in unity settings
then make sure by going and reading the documentation, which is what you should have done in the first place
googling didn't yield clear results
would applying time.delta time be an alternative?
ahh i see
update: runs on frame rate. if it's 30 fps, runs 30 times per second, if it's 60, runs 60 times per second
fixed update: runs on physics simulation rate. by default every 0.02 seconds, approx 50 times per second. used for all physics as it's independent of frame rate
late update: runs after update/fixed update is finished. good for camera updates
niice
i placed it in fixedupdate and it worked like a charm 🙂
thx alot
one more thing
i modified a value in a prefab outside of the prefab
and it wont get updated witht the prefab because of it
fair enough
sorry
so i have this issue with my gaem where there's this rotating platform but the player does not rotate with it. would anyone here be willing to help me figure this out? i know it's kind of a newb question.
yes i tried parenting the player to the platform and that's not working for some reason, it just gets stuck
i suspect it's an issue with the way i rotate the platform
The changes made on the instances of the prefabs won't be applied to them, unless overridden
The prefab can be overridden in Unity's Inspector or programmatically, using the PrefabUtility.ApplyPrefabInstance method
Hoi, I'm working on a portal system that will be able to recursivly render them. The problem I'm having is that when I'm trying to render the camera with UniversalRenderPipeline.RenderSingleCamera(context, portalCamera); it causes a stackoverflow, anyone got any alternative ways of rendering the camera in URP? or any solutions to fix this?
The for the render feature:
https://paste.ofcode.org/5MayTgL3mMCSTxQGYgemdh
Cheers!
weapon is attached by joint btw not becase arm is its parent
I seem to have misunderstood something about rigidbody, for some reason whever I add force to my object no matter what the direction it always shoots upwards. When I press down it moves up slowly (video) when I press up it shoots up fast. When I press left and right it goes left and right but always upwards too. It's like something is gravitating it upwards.
https://gyazo.com/b0dd077094a831174221b5d3d0094831
Debugging script:
public bool down = false;
public bool left = false;
public bool right = false;
[SerializeField] private Rigidbody2D rigidBody;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (up) {
rigidBody.AddForce(new Vector2(transform.position.x, transform.position.y + 1) , ForceMode2D.Impulse);
up = false;
}
if (down)
{
rigidBody.AddForce(new Vector2(transform.position.x, transform.position.y - 1), ForceMode2D.Impulse);
down = false;
}
if (left)
{
rigidBody.AddForce(new Vector2(transform.position.x - 1, transform.position.y), ForceMode2D.Impulse);
left = false;
}
if (right)
{
rigidBody.AddForce(new Vector2(transform.position.x + 1, transform.position.y), ForceMode2D.Impulse);
right = false;
}
}
Anybody got any idea why this is happening?
You're adding the possition as a force, try adding just a float, for ex, new Vector2(0f, 1f) will add a force of 1 to the y and new Vector2(1f, 0f) will add for the x
otherwise if the transform is at position 100, 1000 it will add a force that is 1001 to the y and 100 to the x, and if its in the x direction it will add 101 for the x and 1000 for the y and therefor mostly go up
then it would look smth like this
public bool up = false;
public bool down = false;
public bool left = false;
public bool right = false;
public float force = 10f;
[SerializeField] private Rigidbody2D rigidBody;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (up) {
rigidBody.AddForce(0, force) , ForceMode2D.Impulse);
up = false;
}
if (down)
{
rigidBody.AddForce(new Vector2(0, -force), ForceMode2D.Impulse);
down = false;
}
if (left)
{
rigidBody.AddForce(new Vector2(-force, 0), ForceMode2D.Impulse);
left = false;
}
if (right)
{
rigidBody.AddForce(new Vector2(force, 0), ForceMode2D.Impulse);
right = false;
}
}
ofcourse 😅 thanks I was breaking my head over this.... turns out I should have just read a little closer
thank you!
The position cannot be converted to direction
Hey, im making a dialogue system by inputting a text file into unity and then using a streamreader to read the file. Ive heard that translating the text file into binary will massively optimise the system, is this true and how would i do this? Secondly, I would also like the streamreader to read the file line by line and input each line into a separate line in a Queue, how would I do this?
Here a method should be created, and force should be multiplied by Vector2.up, down etc.
Also, I suppose, else ifs should be added.
The script above was just a debugging tool I added to find out what the problem was, I'm trying to make it work with mouse inputs
This is what I'm working with right now:
public void shoot(GameObject ball)
{
playerManager.losePossesion();
ball.SetActive(true);
Vector3 dir = GetMouseWorldPosition();
Debug.Log(dir);
ball.GetComponent<Rigidbody2D>().AddForce(dir, ForceMode2D.Impulse);
ball.transform.parent = null;
}
public static Vector3 GetMouseWorldPosition() {
Vector3 direction = GetMouseWorldPositionWithZ(Input.mousePosition, Camera.main);
direction.z = 0f;
return direction;
}
public static Vector3 GetMouseWorldPositionWithZ(Vector3 screenPosition, Camera worldCamera)
{
Vector3 worldPosition = worldCamera.ScreenToWorldPoint(screenPosition);
return worldPosition;
}
Which I now realise is not going to work the way I had intended
public void OnColorSliderValueChanged(float value)
{
currentHue = value;
UpdateColor();
}
public void OnLightSliderValueChanged(float value)
{
currentValue = value;
UpdateColor();
}
public void OnSaturationSliderValueChanged(float value)
{
currentSaturation = value;
UpdateColor();
}
private void UpdateColor()
{
Color color = CreateColorFromHSV(currentHue, currentSaturation, currentValue);
cursorPreview.color = color;
icoPreview.color = color;
col = color;
ClientsideNetworkMessenger.instance.SetPlayerColor(color);
}
public Color CreateColorFromHSV(float h, float s, float v)
{
return Color.HSVToRGB(h, s, v);
}```
Do you see any obvious reason why adjusting the Saturation in thos code causes the color to default to red?
private void Update()
{
if (up)
AddForce(Vector2.up, ref up);
else if (down)
AddForce(Vector2.down, ref down);
else if (right)
AddForce(Vector2.right, ref right);
else if (left)
AddForce(Vector2.left, ref left);
}
private void AddForce(Vector2 direction, ref bool value)
{
rigidBody.AddForce(direction * force, ForceMode2D.Impulse);
value = false;
}
Also it's really bad to use booleans this way
^ I know lmao
But I apreciate the input 😄
So what's the problem, currently?
I'd start by debugging currentHue, currentValue and currentSaturation values to make sure they are correct and the hue value doesn't get changed back to 0 or something like that
I think what you and Tapeman have highlighted is that I'm trying to use a location as input while the addForce method is asking for a direction into which to push the object.
Say my Character is at x4 y5 and I'm trying to pass the ball down, I press a spot on the field let's say x1 y3. The way I programmed it now I put that in the add force and it just propells the ball upwards
Still figuring it out how I want to tackle this but I'm on the right track now I think
The force should be added in the direction, which is the difference between the target and current positions
Behold my ugly quick and dirty fix
Im going to clean it up later but this ended up solving it
I based the direction on where I clicked the screen regardless of where the ball currenlty is
Vector2 has a - operator between 2 Vector2s
Can you elaborate?
This means, you can apply the - operator directly on 2 Vector2s
vector = vector1 - vector2
Also, you're supposed to use the target position, not direction, as you have it called dir
aaah like that, gotcha
dk if i can post this here or in #archived-game-design but basically im making a turn based battle system and every enemy has its own special attack pattern so should i just:
jam it all into one script
or make seperate scripts for each enemy or
make a script called EnemyAttacks
The attack pattern is supposed to be a Coroutine, right? You can create an abstract class Enemy for all the enemies to implement its
private abstract IEnumerator Attack();
that seems good but why not use an interface
But not sure how you manage it
i already have a scriptable obj for my enemy for stats and one combat manager script that manages the UI and player turns and everything
You can use that too, but I would rather create an actual class and mark it abstract
public abstract class Enemy : ScriptableObject
{
protected abstract IEnumerator Attack();
}
well why wouldnt interface work or whats the difference bwteen them
interface cannot be even derived from ScriptableObject
ah ok i see i see
well thanks i guess
Because ScriptableObject is not an interface itself
also what does protected do?
You can google that. protected methods can only be accessed within the class and its derived classes
ah i see ok
thanks
whats wrong with sheep
using System.Collections;
using UnityEngine;
using UnityEngine.UIElements;
public class SheepController : MonoBehaviour
{
public float rayDistance = 10f; // Raycasti kaugus
public int rayCount = 36; // Raycastide arv
public LayerMask hitLayers; // Kihid, millele raycast reageerib
public float speed = 5f; //Lamba liikumis kiirus
private Animator animator;
private float rotationSpeed = 5f;
void Start()
{
StartCoroutine(RaycastRoutine());
animator = GetComponent<Animator>();
}
void PerformCircleRaycast()
{
for (int i = 0; i < rayCount; i++)
{
float angle = i * (360f / rayCount);
Vector3 direction = Quaternion.Euler(0, angle, 0) * Vector3.forward;
RaycastHit hit;
if (Physics.Raycast(transform.position, direction, out hit, rayDistance, hitLayers))
{
Debug.Log("Tabasime " + hit.collider.name + " suunas " + direction);
transform.Translate(-direction * speed * Time.fixedDeltaTime);
Vector3 targetDirection = hit.point - transform.position;
targetDirection.y = 0;
Quaternion targetRotation = Quaternion.LookRotation(-targetDirection);
transform.rotation = Quaternion.Slerp(transform.rotation,targetRotation , rotationSpeed * Time.deltaTime);
animator.Play("Run");
}
else
{
animator.Play("Idle");
}
Debug.DrawRay(transform.position, direction * rayDistance, Color.red);
}
}
private IEnumerator RaycastRoutine()
{
while (true)
{
yield return new WaitForSeconds(0.01f);
PerformCircleRaycast();
}
}
}
First up, use a SphereCollider and react to collision events or use CastSphere instead of 360 different raycasts, ill look at the rest now to figure out what causes the movement
Please ask the question directly instead of asking for general help 😄
Oh ok I'm not used to this thing
secondly compare the hit.other.transform.position with transform.position not the hit position which might be inconsistent
Please post the relevant !code here
📃 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.
hard to see anything on a phone recording 😄
how about start with the relevant one
use links
I don't know which one is the faulty one that's the problem
show us the one that would handle the collision with the wall
game manager this one
ok wait
where is the one that supposed to increase point