#archived-code-general
1 messages · Page 231 of 1
Haha
my problem here seems to be hyper niche
@misty ibex I really have no idea what could be causing the issue, everything does seem correct. I wish you the best of luck with getting it working though!
Would modding questions go in this chat?
modding discussions should be directed to the community for the game you are modding, they are not allowed here
Well, unless you're asking how to make your own game moddable, but that seems like some research of your own.
Yes, it's this.
I'm looking to pair human advice with what I read online in forums and other locations . A well-rounded idea of what to do/not to do/etc.
well then that's not really a modding question. but also https://dontasktoask.com
fair enough, i think you for your attempt tho
Is there a way to check if a dictionary contains no key, value pairs I.e if they have all been removed
its Count property will be 0 if it contains no objects
that's what I was looking for thankss
I'm .. stumped.. What else could control which scene starts from editor play mode? I wrote some code a long time ago to force it to a loading scene, but .. commented that bit out and I'm still starting from the loading scene (instead of the current scene in the editor)
do you have a game manager script in your scenes?
In my loading scene, yes, but in this new scene it's .. empty-ish.
I do have some "load first utils" in a script but nothing that should be ... doing anything that would instantiate anything?
Nothing is in the "Test Spine Character Rigs" scene and yet.. somehow my app gets forced back to the Loading scene
nothing in the codebase with InitializeOnLoad, nothing even that controls scenes that exists outside of my own scene manager which is instantiated after the game loads the loading scene....
Perhaps that code affects the whole editor session if it run once?
yeah that could be it
oh, good thought
maybe the settings are somehow still being loaded
can i force the editor dll to be recompiled?
trying rebooting
(aside from restarting unity)
oh, wait, no - that's not it.. see that line that's commented out that warns? I see that in the logging as expected
"forcing scene to 0"
Oh, wait. Does DDOL persist between plays?
I see the DDOL "scene" appear when I press play
This would imply that your code is still running.
wtf.. The funny thing is most of the google results are how to avoid this behaviour and start from a fixed scene 😛
Your commenting out probably didn't save or get compiled.
Make sure the editor refreshed after your changes.
negative ghost rider, code's still compiling
note "player manager awakened" - there's no player manager in that scene (or anything, actually)
..? So it didn't print?
"dlich likes candy" followed by commented out lines of scene redirection
brb phone
Where is the rest of the stuff getting printed from?
those are a bunch of game objects that exist in LoadingScene
I'll restart the editor but.. still don't quite understand what would be causing it since that code is clearly compiled/updated (and the part that's sending the scene to [0] is commented out)
You're messing with the editor runtime. Which I'm not sure resets between domain reloads.
Weird, now it works. Interestingly, I see the "dlich likes candy" as soon as I start the editor (before I hit play once)
And yeah.. I suppose the editor compilation of the editor code only happens at some sort of .. editor domain reload? while the play mode compilation occurs on demand
It's not related to code compilation lol
It's the runtime that is not being reset. Which is totally normal for programs.
well I mean that bit of code there in the InitializeOnLoad doesn't .. get updated if I recompile/play. Isn't that part of the domain reload?
Any way I can.. have it do so? re-instantiate the static LoadFirstUtils?
Don't mess with editor scene manager in the first place 🤷♂️
I know how to use "normals" to make a projectile bounce off walls
how could I "project" that path with a laser?
(like an ingame laser...not necessarily a raycast laser)
@thick socket You could use the LineRenderer component although I don't think they can be bounced off walls
ooh perfect thanks
1): draw lineRenderer to wall
2): raycast to wall to determine the bounce angle
3): draw another lineRenderer from the wall position with the bounce angle
4): repeat
not sure how "pretty" line renderers will be
but worth looking into
👍
How is Unity.Mathematics.Random meant to be used? All examples I can find online just hardcode a number when initializing it, and some dont even bother, others suggest to use DateTime.Now.Millisecond or .Ticks, but the constructor only takes a uint, and .Ticks is a long (while Millisecond is an int), and converting or casting Ticks restricts the long to int.MaxValue (which makes sense) - in those cases random will always be the same seed anyway, though with this code im always getting min (in this case, 5), even with a different seed, is there another way its meant to be used or am I missing something in the logic?
public static int GetRandom()
{
var rng = new Unity.Mathematics.Random(System.Convert.ToUInt32(System.DateTime.Now.Millisecond + 1));
var rnd = rng.NextInt(5, 10);
Debug.Log((System.Convert.ToUInt32(System.DateTime.Now.Millisecond)) + " | " + rnd);
return rnd;
}
According to the docs, .NextInt is exclusive, so id expect a value between 5 and 9, but I always get 5 (or whatever I set as min), why might that be?
I'm assuming you're reseeding it every call to the function. Try seeding once only?
What did the log print?
Millisecond plus one btw for the printing
i use unityengine.random.range to seed it
Can python be used in unity
Unity uses C# officially. I'm not aware of any other language supported.
i remember they created a new extension so that you can use python, but i dont know the details, google it
Ok i will thank you
Seeding it once did seem to randomize it more often than not (still returns 5 quite often but that might be only having 5 numbers to choose from), though if the suggested usage with Random is to seed with millisecond/tick, wouldnt you want to update the seed every time you use it, as new miliseconds/ticks would have passed since the last use? - for the prints, I do get the current milisecond between 1 and 999 (as online suggested the constructor errors with a millisecond of 0)
not sure if you can use python in game script
I have a whole game in python 2d text based i want to translate to unity 2d mobile with ui
Any way to make scripts constant through multiple scenes?
Like i wanna declare a ton of variable when people load in
You can install Python Scripting in the Package Manager
What's the actual print result?
Thank you sir
If the seed values are all the same the results will all be the same - first element.
You're welcome, but you should consider using C#, by using Python you will most likely be slowing down your game, and you won't be able to get coding support in the Code Support channels. Plus all of the tutorials online and forum posts around coding are in C#.
Ok i will try
I also wouldn't be surprised if unity Deprecated their Python scripting package soon, I'm surprised they even have one.
Last question srry electro
I couldnt find a answer online
What is the question?
c# or python script?
Any way to make variables constant through multiple scenes
Like i add a ton of variables in beginning
And trace them later on
not sure what you want: constant or static variable
Constant
ScriptableObjects could work. You could also make game objects set to DontDestroyOnLoad which will bring Game Objects and their scripts across scenes.
first number is the milliseconds, second is Unity.Mathematics.Random and last is System.Random if I run it a few times, ill get different numbers for all of them, but usually 5 for the last 2
I believe
Like i want to say
recruitableqb1 = “Johnson John” could i trace this later
u cant modifiy constant in runtime, it is compile time defined
constant modifier
or readonly static
So consider trying to acquire a different value for seed
So no?
Interesting, do you just use the min and max values your wanting to randomize as the params with the seed? Like new Unity.Mathematics.Random(UnityEngine.Random.Range(min, max) or something else?
yes, though the range of seed in mathematics.random is uint, but easy to write
As I mentioned above, you can use ScriptableObjects or DontDestroyOnLoad() on your game object to access variables across scenes.
or just unchecked the return value of random.range to keep the bit pattern
Sorry im not sure I understand - right now this is what im doing:
static System.Random r1 = new System.Random(System.DateTime.Now.Millisecond + 1);
static Unity.Mathematics.Random r2 = new Unity.Mathematics.Random(System.Convert.ToUInt32(System.DateTime.Now.Millisecond + 1));
public static int GetRandom()
{
var rnd = r2.NextInt(5, 10);
var rnd2 = r1.Next(5, 10);
Debug.Log((System.Convert.ToUInt32(System.DateTime.Now.Millisecond)) + " | " + rnd + " | " + rnd2);
return rnd;
}
The seed is now only being set once, are you suggesting to use a hard coded value for the seed instead or a larger number?
@muted valley Have I answered your question?
You're welcome.
Time to get to work tmmrw
You're not supposed to reseed per call to random
Oh sorry, I forgot to remove the var rng part, I wasnt using it in that snippet just testing - though I thought you were meant to use the latest value of tick/millisecond when you wanted to make sure the value youd get back is not always the same most of the time, when should you usually reseed Random?
Never again unless you're wanting to explicitly reset random to a default initial state with a given seed.
You'd seed once and simply call next whenever you're needing a random whatever.
Ah ok, one last question, if the value is only meant to be passed once, does the value of the seed not affect the results? It makes sense why it would reset to the initial value (as to why I always got the min) im just trying to understand why using the current millisecond/tick is often suggested over just a hardcoded value or someone mentioned with using UnityEngine.Random to generate a seed, is it just preference?
A hard coded seed value will always give you the same result - which you might want for certain games. You can use anything to initially seed it. Oftentimes the current time in milliseconds or some not so predictable value.
Ah I see, thanks for the info and help on this
is there a way to pre-calculate the magnitude of a rigid body before applying a force to it?
IE if(rb.addforce's magnitude < maxMagnitude){ rd.addforce;}
Was able to make something that got close enough...
||May or may not have GPT'd this one||
Vector3 currentVel = body.velocity;
Vector3 acceleration = force / body.mass;
Vector3 dragForce = -dragCoefficient * currentVel;
acceleration += dragForce / body.mass;
Vector3 predictedVelocity = currentVel + acceleration * Time.deltaTime;
float estimatedMagnitude = predictedVelocity.magnitude;
return estimatedMagnitude;
}```
I do not believe this will work with any other forcemodes other than force.
Also note that any forces outside of drag wont be accounted for unless added, so things like gravity will mess with the prediction
Final thing to note is that the dragCoefficient is some arbitrary constant that I made up... In testing I used 0.1 which works but Im sure a much better constant can be found without much work
Ya know I just realized how pointless this is for my use case but it exists now I guess
hello devs, do someone know how to calculate proper position,
i have problem - particles should emit at collision point but it differs according world position of collision point, and i've made wrong position calcs
Custom_SimSpace_Transform is "ParticlesSystem's" Custom Simulation Space and it is located at center of car
here is script , thx in advance
private void OnCollisionEnter(Collision collision)
{
var emitParams = new ParticleSystem.EmitParams();
+ // IF I USE
- /* emitParams.position = new Vector3(0, 0, 0); */
+ // It will emit particles at "Custom_SimSpace_Transform" it is -> for example at (257,533,1043) in world postition . in other words it'll emits at center of car
+ // So i made this thing bellow
emitParams.position = Custom_SimSpace_Transform.position - collision.contacts[0].point; <--- I assume ,Issue is here
+ // But it works not right as shown in video
emitParams.applyShapeToPosition = true;
Emit_1_obj.Emit(emitParams, 30);
}
Hey, guys, does someone know how to write a script to alternate between two different sprites based on a key input? I'm remaking Flappy Bird and need to switch between two sprites of wings flapping for each spacebar input.
not code general
https://docs.unity3d.com/Manual/class-SpriteRenderer.html
wtf how did you do highlighting?
He's using the diff lang tag
fancy, never seen that before
With + and - on the necessary lines.
You won't get proper c# syntax highlighting with it though.
Tranform.position calculation help
i get null refrence here
Fix it.
Code tip. Instead of doing spawnPoints[_index] every time you want to access the element, just do
var spawnPoint = spawnPoints[_index];
and use the spawnPoint variable instead
will make things a lot easier to read
also faster
like this?
If it's intended to create a new instance there, yeah.
Show the error in the Unity console
Show an image of the error from the unity console
well making an instance fixed it
looks like resistance is reference type
and you just create an array of reference but you didnt actually create the instance
The potential for error is quite high due to i being constrained to spawn point resistance length solely and not enemy point resistance length - not related to the specific error but should be considered.
You could also clear up some clutter by having local variable references of the elements being accessed from the arrays.
var enm = ...
var point = spawnPoints[_index];
...
for (int i = 0; i < point.resistance.Length && i < enm.resistance.Length; ++i)
{
var enmRes = enm.resistance[i];
var pointRes = point.resistance[i];
point.sprite.enabled = true;
pointRes.type = enmRes.type;//NRE here would mean that the element is null
pointRes.modifier = enmRes.modifier;
}```
maybe stupid question
I have a list List<SystemBase> systems
Is it possible to go through the list to get exactly the heir (automatically bring the system to the class of the heir)?
What do you mean by "heir"? The derived class?
I am leaving all my methods and fields to my heir.
And nothing for my good-for-nothing daughter.
I could see an alternate reality where the child/derived class was called the heir class.
It's not like programmers are strangers to giving multiple names to the same structures/concepts.
Method
Function
Map
Dictionary
method and function do have different meanings
but function sounds cooler
same with vectors vs list
i just call dictionary/hashmap/hashtable/array/unordered_map mapping
maps A to B
Hi all, would you know how to add force (impulse) to CharacterController to Jump? Any ideas?
You would need to use a Rigidbody to add an impulse force. This is the code I use for CharacterController jumping.
velocity.y = Mathf.Sqrt(jumpHeight * 2 * -gravity);```
The docs for the character controller have an example on how to make them jump: https://docs.unity3d.com/ScriptReference/CharacterController.Move.html
Is there any way to check that there isn't any particles inside sphere? Like CheckSphere(), but seems CheckSphere() doesn't work with particles.
What particle system are you using?
Is there a way to make objects permanently lockable/unselectable in the Scene View? There are certain VFX I have in my game that use large cubes and quad meshes with alpha clipping and transparency that I don't EVER want to be able to select from the scene view. To get around this, I can toggle picking on them in the Hierarchy or Layers options but Unity always seems to arbitrarily reset these options and there doesn't seem to be a good way to modifiy them via editor scripts. Am I missing something totally basic that would solve this problem?
You can use this: https://docs.unity3d.com/ScriptReference/ParticleSystem.GetParticles.html to get the particles at a given frame and then check their location relative to your sphere.
Thanks, I will try it
I think it's the https://docs.unity3d.com/ScriptReference/SceneVisibilityManager.html SceneVisibilityManager's job
I need a bit of physics help again. My blue circle is moving down through the red edge colliders (which are both a part of one composite/custom collider). The red colliders are supposed to have a one-way effector. When I use .Cast, the blue ball only gets a hit on the upper red edge shape, which it has been told to ignore because it is in the middle of it. How do I detect the lower shape?
assume my blue ball-like colliders could get complex, so raycasting from each lower surface individually is not a good idea
You could use the version of raycast that returns an array of results and get both
Hero! I could not find this. Going to give it a shot 🤞
I’m not exactly sure which one you mean? A lot of the casting methods for 2D only produce one RaycastHit2D per collider hit (even if they return an array)
(sorry if I didn’t specify 2D earlier)
In 3D you would use Physics.RaycastAll to receive a list of all hits
The red bars are a single collider?
yes. both are part of a composite collider produced from a single tilemapcollider2D
tilemapcollider2D have been making things more complicated in terms of physics tbh
That's tricky
doesn't make sense to have RB with CharController
yeah. I’m thinking I might need to query the composite, and make a series of customcollider2D for bundles of shapes. But it seems like a hackey solution that contradicts the point of a composite collider
You might want to consider a two step raycast, with the second starting at the hit point of the first if the first is within some distance to the center of your blue ball.
Which is why I gave you code for CharacterController jumping
I'm confused, I saw there RB only, maybe you edited, not sure.
Anyway, I have that code there. Not working :/ I'm trying to do the jump like 5th time. Never had an issue in 2D. I don't even know my name how angry I am (doing 3D movement first time for last 50 hours).. never had an issue with complex coding of various systems, but seems like 3D caught me unprepared 😄
that might cause issues later when my colliders get more complex, as raycasts are similarly expensive to casting a polygon, but i’d need several to handle more complex geometries.
I did not edit it. Can you confirm the code is being ran? I'd recommend using a Debug.Log("jump test"); to check
maybe unity just doesn’t give the tools to query this for 2D
use a layer mask or use the version of collider.Cast that takes multuple results
the issue is the red lines are all part of one collider
.Cast only gives me one hit result per collider
Unless there is some setting idk about
ah yeah didn't realize that. Is it not possible to split that collider somehow?
You can also try doing another cast from the other direction
i could split the collider, but I would need to potentially make 100 colliders separately to split it
example hard case
i would be ok with the top right part of the blue either ignoring or registering the widest red shape. But i need to know that I would detect the bottom red shape.
yeah i'd do a staged raycast here
but definitely hard with the complex shape
What's the use case of this?
my semisolid (one way) platforms are generated by a single tilemap for a level. They all feed into one composite collider.
The blue blocks are blocks of arbitrary shape that can be made and pushed around
blue blocks are made by one tilemap => composite collider
Why do you need to raycast to get the lowest platform?
I think you might need to make them not one composite collider as the most straightforward solution
I expect in that scenario that the blue block could at least lay on the lowest platform
i worry this will be the case, but I will need to turn one collider into ~100 colliders. So I worry performance will be suck.
do you really need all of them at once?
How many platforms will be on screen at a time
potentially many. it is a maker-style game
so nothing would stop the player from just drawing a bunch of platforms in a weird line like that
I'm not completely sure I understand the use case but you could try getting the corners of your custom shape and doing raycasts from the lowest ones, that would probably find your platforms.
the normal unity way is to make each platform one gameobject.
Or even from all the corners, and getting the best platform to rest on.
that might be the solution, but since this is for a custom physics engine, 20 raycasts for a complex shape every frame is like 20x more expensive for the most expensive part of my little physics simulation
i have just benchmarked Collider2D.Cast vs Raycast. Both are weirdly very close in cost
You could do a single corner per physics step, or frame, so the cost would be fixed but the accuracy would go down as your shape gets more complicated.
Single or fixed number.
all these solutions just feel so expensive because the shapes can have arbitrary sizes 
There's always a limit of some kind.
it just feels like a really silly reason for the limitation
just that the cast only gives one hit per collider instead of per shape
You can alternatively choose to have many colliders, it's just another performance consideration.
How much of this do you have running right now?
would you know how the scalign is in terms of cost? 1 composite with 100 shapes vs 100 custom colliders with 1 shape each?
what do you mean?
The only really good way to measure is to test in your project. How much of this have your built?
my physics engine is like 95% done. Just working out some last oddities/bugs
custom solver… however you want to say it
So pick one of the above options and profile. Measure on a target device. See what the cost is, scale various factors and find out how much works and to what scale.
It's the only way to be sure 👽
makes sense
You may be surprised what you can get away with.
yeah, I just want to avoid the kind of surprises of players breaking the game in terms of unintended lag
profile first and worry later
btw feature request wise: it would be nice if CustomCollider2D were not a sealed class. So you could just inherit and make your own collider classes with their own parameters
it’s just a lot harder to use customcolliders when inheritance isn’t allowed
protected bool explodesIntoMoreFireballs = false;
I have a class extend the class this is declared in...is there a way to have the extended class make this into a Serialized Field?
no
darn, thanks 🙂
why not just serialize it
Dont want the extra "garbage" on more classes
you probably can achieve this with custom editor if your field is [HideInInspector] public
If I was redoing my AI in the future I probably would figure out a serializable way to do it
however I've only got 3 enemies left so dont wanna re-configure it all rn 😄
Hello, I want to make an animation listener for server client infrastructure. The client gets the state it is in with stateInfo.fullPathHash and updates the animID in its object to other clients, if the script animatorType == server, it updates the animator with the animID from the server, but I have problems with loop animations like walking, idle. How should I use the data I get from stateInfo.fullPathHash or are there any other methods you can suggest?
void Update()
{
if (animatorType == animatorType.client)
{
AnimatorStateInfo stateInfo = animator.GetCurrentAnimatorStateInfo(0);
int currentStateID = stateInfo.fullPathHash;
animID = currentStateID;
Debug.Log("currentanim Hash" + currentStateID);
}
//remove the query prevAnimID != animID I tried refreshing it continuously, but it had no effect.
//I also tried animator.Play(animID, 0, 0f); but the problem is still the same
if (animatorType == animatorType.Server && prevAnimID != animID)
{
animator.CrossFade(animID, 0.2f);
prevAnimID = animID;
}
}
video: https://youtu.be/PfmqvWi__7I
have you looked at the source code of the unity component that does this?
you can also refer to mirror's implementation: https://github.com/MirrorNetworking/Mirror/blob/master/Assets/Mirror/Components/NetworkAnimator.cs
I'll check it out, thanks.
This might seem like a super silly question, but it is a gap in my knowledge. I understand I can't play DirectX games on linux, but can I build a StandaloneWindows64 target on linux and use DirectX for the graphics API
are you trying to replicate animation state in unity to something else, like a website?
Aka -Can I build a D3D Game on Linux for Windows
don't see why not
yes
Using the unity headless, is there a parameter I can pass that will force only using D3D graphics API ?
what is your objective?
you are at the start of a long journey if you are trying to render headlessly
I am using game-ci to build our client - every time it builds it fails compiling our shaders because of GLES
I did not fully understand, but in short, I am trying to write a large-scale tcp udp server client. like mmorpg
definitely study the mirror code
i have bad news. game-ci doesn't really work
for everything but the simplest projects
Yeah - this would not be that unfortunately
So for CI (aside from using Cloud Builder , which will explore) do you recommend just doing a script
where does the CI have to occur? what is its purpose?
I have a PowerShell script that I use atm that works on windows and headless
We would like it to occure in Github using Github ACtions
purpose is to just make our life easier and be able to reduce depedencies on people to do an internal build
i guess, bigger picture, the goal is to save money? you will have to pay for a unity license anyway to run on github actions
Oh no we will still pay for a license
yeah i guess i'm saying that cloud build is what you should use
Thank you very much
. I thought about looking in the mirror, but I'm a bit lazy. I think the best way is to examine the mirror.
because you will not succeed in building a complex project in CI in the short term. it will take a really painfully large amount of product development
We would like to keep our build systems all in th esame place if we can
As we have other tools that aren't unity
well... it's impracticable*. this is coming from someone who has built a general CI for unity
i'm not saying it's impossible
Thats unfortunate
you will never be able to build il2cpp windows correctly on github actions, for example.
anyway, you should use cloud build
i have definitely tried to raise issues with game-ci in the past, and they were ignored
so i feel the same pain as you
yeah atm, I just have a Github Self-hosted runner that execute a headless powershell script
it's ultimately one guy. he doesn't have the bandwidth to test people's projects
that's pretty much the worst possible setup lol
ha - well it does work pretty well atm
I just hate windows and would prefer it to build on linux
so if I can solve for the D3D problem, I am fairly comfortable with the rest , so long as their aren't other Unity issues
Ah - we are the opposite
you definitely, absolutely cannot build unity on linux for anything but the most simple projects
I am leaning that 🙂
couple of our shaders throw up when compiling with Volkan , which is why Iw as asking about forcing D3D
you shouldn't have issues compiling to vulkan on any platform
it is very easy to specify the graphics devices though
well... that's a real error
are you using ASE?
Ha - I am not a shader guy - so I have no idea what that is 🙂
I'll have to ask - I don't thin so
they're going to tell you this is an issue with your project
you don't specify the linux build target when building for windows, so you never have to build for vulkan anyway
so i think there are some basics you haven't figured out yet
Fact
And that does make sense - infact in our project settings, we specify the graphics API for the windows target
I am wondering if this is a game-ci thing
@polar marten Answer to your question - no we did not use ASE , just built in unity shader graph
any way to pass a custom parameter to SceneManager.sceneLoaded ?
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
}
it looks like this
so i cant add custom params
No you can't. What parameter do you want to pass?
ID of some sort
You could create your own function in your own script that can take in extra parameters.
why would you even think that you can change the signature of a method?
im explaining the situation
Why do you need to pass an ID anyways?
The scene reference contains an index and the name. Would that work for your id?
no, you are asking something fundamental to C#
A method has been defined with a signature, can I call it with a different signature. Of course the answer is no
Ask in #✨┃vfx-and-particles as this is not a code question
Just reading over the Unity.Logging code, and I have seen a continued theme on Unities new packages. Why does Unity hate people modifying their code so much? Like the Unity.Logging.Logger has no virtual methods, poor documentation. Like I just want to be able to make a Logger with a specific decorator for the class Type that I pass it to with my Dependancy Injection framework
If you update Unity, the code you modified will be changed.
I think you miss understood. I am not trying to modify the source code, but inherit the class to make custom implementation
Thus virtual
Oh I see
That's a good point
But do you really need to create a custom logger? In most cases it will meet the needs of the user considering all it does it log messages for debugging purposes
Anyone who has used actually good logging frameworks have more needs then what they offer. I have Serilog working, but the adapter for it and Unity is rough at best, so was hopping this had more potential
What if you create your own logger? I'm sure it is possible since you can create editor windows.
What? I think you are talking about the console, vs the logging framework. Console is responsible for the display of the logs, which I am using Seq, and there are assets on the store that have better editor consoles. The logging framework is what gets/formats the logs, and then sends it to sinks(like console/file/seq/database)
Ah, well why not create your own logging framework?
I figured out how to do what I wanted. using
Log.Logger = new Logger(new LoggerConfig()
.MinimumLevel.Debug()
.OutputTemplate("{Timestamp} - {Level} - {Message}")
.WriteTo.File("..absolutPath.../LogName.log", minLevel: LogLevel.Verbose)
.WriteTo.StdOut(outputTemplate: "{Level} || {Timestamp} || {Message}"));
and my DI framework I can just hardcode the type in the logger I inject.
There are problems with Unities console as a sink. I have tried
That's good. Well good luck with what ever you're trying to do!
Update: It works.... It's just ugly af
hello I have a problem in my code. it doesn't want to take "else" please help me, thank you
You're missing brackets. This is a #💻┃code-beginner question.
It doesn't want to take the entire function tbh
You're also misspelling your reference to your sprite renderer
Hey at least their VS is configured properly
But yeah you're missing a bunch of curly brackets, and that's what's making it angry
void Flip()
{
if()
{
//flipX = false
}
else if ()
{
//flipX = true
}
}
how do i average two vectors
Like you would with two numbers
Add them, divide by two
Or you can do a fancy Vector3.Lerp(a, b, 0.5f) to get the mid-point between the two, which is the average
new is not expected here, Lerp is a method
got it ty
Hm seeing your code, you seem to average two direction vectors, so you'd be better off using Slerp which will give off a normalized vector out of the box
So I am setting up my bootstrap scene loading. Currently if I have multiple scenes loaded in editor with bootstrap not the first one, the other scenes scripts will be called first. I tried to get all active scenes, and unload any but bootstrap and then reload them, but they won't unload on
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
I can't find a way to reorder the load order of active scenes in the manager. Does anyone know how to do this?
I bought a new pc and am trying to open up my project in the same exact editor version, but all script links are broken and prefab links as well. (game objects have missing links to their prefabs, linked game objects are broken as well). I brought the exact same code that was pushed from the other pc via git, so there is not a single change that i dont have on the new pc. what am i missing?
Hello i have a quick question. I dont really understand how audio sources work. I am using them to make 3d sounds. I get how to set them up and do the range and everything and it works how I want it to. Now im having issues where in my script I am trying to play a 3d sound. I cant really get it to work and it isnt doing the distances right. ```using System.Collections;
public AudioSource flickerSoundOn;
public AudioSource flickerSoundOff;
private readonly float offDuration = 0.2f; // Fixed duration for which the light is off
IEnumerator Flicker()
{
while (true)
{
// Turn the light off and apply the off material
lightToFlicker.enabled = false;
objectRenderer.material = offMaterial;
flickerSoundOff.Play();
// Wait for a fixed duration of 0.2 seconds
yield return new WaitForSeconds(offDuration);
// Turn the light back on and apply the on material
lightToFlicker.enabled = true;
objectRenderer.material = onMaterial;
flickerSoundOn.Play();
// Wait for a random time before turning the light off again
float waitTime = Random.Range(minTime, maxTime);
yield return new WaitForSeconds(waitTime);
object
I cut the code cuz it was long. But do I just make an empty object that has the audio source and refference that?
What I'd do is only use one AudioSource placed correctly in the world. The script references it, as you have it now.
Then the script would also reference two AudioClip in which you'll drag-drop the sound effects, and call source.PlayOneShot(clip). This has the advantage of using one source to play a variety of sounds, without the sounds cutting each other out if you play them fast enough for them to overlap a bit
Oh hm I see. So make an audio source in the object that I want to change and then that audio source gets recieved the clip from the code and plays there?
Yep, in that case you don't drag-drop the clip to play in the Audio Source, but in the script
I see. Thing is. On the object I want to make this flickering sound I already have an audio source constantly emitting a hum. So would I just make another audio source as a component. If so how would I access that one in my code? Sorry im really new to this need to watch a video or smth
Yeah you can have another one on the same object, and you'd have to drag-drop it into your script.
Place your cursor where it says "Audio Source", and start the drag-drop from here
Ok thank you so much. Im going to quickly try and if it doesnt work ill probs text again lol. but thanks
Is there a more performant way to stop all components that have [ExecuteAlways] from running than doing
foreach (var comp in go.GetComponentsInChildren<MonoBehaviour>())
comp.enable = false;
Basically I only want to render a GO, not have any of its logic execute.
Could seperate the logic from the render
Wait am I allowed to send you my entire like long code or will I get in trouble. Cuz I made a change but still need a bit of help if thats okay
so you only need to disable the logic GO
Sure, if it's long post it in a paste website as per the instructions below: !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.
Okay yeah thats what i was looking for. Its not that long but dont wanna disturb. gonna send it rn tyy
It is for an editor tool. I am creating previews of prefab assets. And when I Instantiate them to render a preview, the code is running. I don't own the prefabs.
https://hastebin.com/share/xanevedawi.csharp okay so this is my code now. Im still kinda confused on how to get the right audio source to play
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Do I just drag and drop it
where I set the audio source at the top
Yes, but to be able to see it in the Inspector, you need to make it public like the two clips
Oh yeah idk why i made it private that was dumb of me
And then also remove the lines 25-28 which will overwrite the value you drag-dropped
Wait whats the difference between readonly and private.
Read-only is well, read-only. You can't put a new value into it with =
Private is not visible outside of the class
Oh I see so once you set a read only it cant ever be changed. Thats interesting. Thank you so much for the help I figured out the other thing aswell just drag and dropped it
Oh neat I been wanting to do that for my tool. How does that work exactly? Do you need to instantiate the GO first or can you directly render it from the asset/resources?
Readonly can only be assigned inline, or in a constructor if you're using a plain c# class
Wait im having an issue still
I did what you said and dragged and dropped it in but its still not playing in seperate audio sources
I want it from the second one
Did you remove the lines in void Start() that fetch an AudioSource again, overwriting what's in the variable?
I removed the ones you told me to i think\
rn its just this
{
if (lightToFlicker == null)
{
lightToFlicker = GetComponent<Light>();
}-------
audioSource = GetComponent<AudioSource>();
StartCoroutine(Flicker());
}```
The one in the middle of that code still puts a new value into it
audioSource = - puts a new value into the variable
It says "Look for the first AudioSource component you can find on this object, and put its reference into the variable"
The 'right' way to do it is to create a preview scene EditorSceneManager.NewPreviewScene() which you can add a camera and lights to, and then instantiate the GO and add it to that scene. Then you render the camera to a RenderTexture.
Ah, neat. I would expect to use another type of dummy prefab just for the render and point it to the actual prefab when I'd select it. Having to instantiate the actual logical scripts seem odd when you just need to render it.
Yeah it is a bit annoying. You could technically just find all the render components and copy them over to a new GameObject. But I think that would be worse for performance, and you would have to also copy over the transforms and children and stuff.
Using the preview scene is how Unity does all of the renders and previews of things internally too.
Any one does have any idea about why this is happening? I'm just trying to spawn an prefab on client and host...
This is the class
using Unity.Netcode;
using UnityEngine;
public class TestPrefabSpawner : NetworkBehaviour
{
[SerializeField]
private GameObject _NetworkPrefabToSpawn;
public override void OnNetworkSpawn()
{
Logger.Info($"Spawned with Network.");
}
private void Update()
{
if (!Input.GetKeyDown(KeyCode.Return))
return;
if (IsOwner)
{
if (IsServer)
SpawnPrefabClientRpc(LocalPlayer.Transform.position, OwnerClientId);
if (!IsServer)
SpawnPrefabServerRpc(LocalPlayer.Transform.position, OwnerClientId);
}
}
[ClientRpc]
private void SpawnPrefabClientRpc(Vector3 position, ulong id)
{
var instance = Instantiate(_NetworkPrefabToSpawn, position, Quaternion.identity);
instance.GetComponent<NetworkObject>().SpawnAsPlayerObject(id);
}
[ServerRpc(RequireOwnership = false)]
private void SpawnPrefabServerRpc(Vector3 position, ulong id)
{
SpawnPrefabClientRpc(position, id);
}
}
And it's a direct children of the player network object
I'm this close 🤏 to give up on 5 months of work because of this
For context, the prefab is being spawned on the host and visible on the client. But this error is triggered when the client tries to spawn the prefab from the ServerRpc
Hey. I am trying to bake a nav mesh. Why is this happening this gap?
Make sure there are no colliders in that gap. Or NavMeshObstacles etc.
Oh wait I see. I used pro builder to make a gap in that wall. Apparently unity still thinks there is a wall there. Do you know how I can fix that?
No idea about probuilder. Is there some leftover invisible object?
You baked again after removing it, right?
try checking out the size of your navmeshAgent, sometimes it's too thick
You might wanna try in #archived-networking
oh, ty
What object is selected/outlined here? Looks like that object actually has a gap. Hide it and show what remain?
Its the wall selected
Ok looks like it still has mesh data but no materials or something... you probably need to fix that with probuilder somehow
Maybe someone here #🛠️┃probuilder can help
Ah
Didnt realize that was a thing thanks
I have a nav mesh setup with a sprite renderer set to follow my player. How do i set the direction the nav mesh faces. It is coming backwards towards me
It works when I make the material double sided and regular but I want it to be affected by lights so I put diffuse on
How do i set the direction the nav mesh faces
Do you mean the sprite renderer instead of navmesh?
Sprite renderer sorry yeah
It doesnt face the right way that the nav mesh makes it face and walk
Should it face the camera or should it use the rotation of the player?
Idk ig face towards the camera. Rn the nav mesh AI seems to be running its direction already ```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class testMonster : MonoBehaviour
{
public NavMeshAgent ai;
public Transform player;
Vector3 dest;
// Update is called once per frame
void Update()
{
dest = player.position;
ai.destination = dest;
}
}``` this was all the code
If you want the spriterenderer to face the camera, you can use LateUpdate, set its rotation to the camera rotation and then rotate it 180 degrees on Y
Why would this work fine
buttonGameObject.transform.Find("IconContainer/Text_Index").gameObject.GetComponent(TextMeshProUGUI).text
But this throws an error
buttonGameObject.transform.Find("IconContainer/Text_Index").gameObject.GetComponent<TextMeshProUGUI>()
And this only works in immediate window. The first code won't even compile!
Show the whole line of code. Neither of those would compile as is, and neither make sense to even use as is.
You really would want to separate the calls instead of one long chain too. Find on its own line GetComponent on another
selectedPlayerIndex = Int32.Parse(buttonGameObject.transform.Find("IconContainer/Text_Index").gameObject.GetComponent(TextMeshProUGUI).text);
is how it goes. I have a Text_Index child object inside of the main gameobject where it stores an index in a TextMeshPro component
But I can't get it to compile. Although if I do this in immediate window, it works
What compile errors does it throw?
Seems like you're using GetComponent .method incorrectly. Read the error and look at the method documentation.
Why would it work in immediate window then?
No clue. I wouldn't recommend relying on the immediate mode with unity, as it's not a regular C# program. It relies on the C++ side a lot.
The reason I started debugging through immediate is because I couldn't get the .GetComponent working at all in code.
You should check it's documentation. The generic method was correct.
You probably didn't have the component on the GameObject
Ok, will doublecheck everything. I just found it odd that code worked in immediate but not when running. Thanks
I lost my usb with a project on it 💀 is there any way to recover it or am i screwed
How can you possibly recover something that was physically on something else?
This is the reason you should be using version control which keeps your project on the cloud
So unless you find the USB, take this as a learning moment and learn how to use version control before you start your project again
Do you have the project on anything other than the usb?
Like a backup I mean?
Hi, not sure if this is the right channel but I'm trying to code a 2d character throwing a grenade at the player. I have this as the angle calculation
Vector2 final = new Vector2(Mathf.Cos(angle * Mathf.Deg2Rad), Mathf.Sin(angle * Mathf.Deg2Rad));
throwGrenade.GetComponent<Rigidbody2D>().AddForce(new Vector2(final.x * force, final.y * force), ForceMode2D.Impulse);
the enemy is not throwing it in the right direction and I'm not sure why
First, use SignedAngle
Otherwise you get the delta amount instead of the Real delta
Is only the direction or also the trajectory wrong?
I have no idea, it's all kinds of messed up
when player is near 0,0 it seems to work right
but if player moves anywhere else it doesn't aim right
Then try the signedAngle approach
I just want the direction right
Instead of Vector3.Angle
I did signed angle and it didnt' change anything
I did Vector2.SignedAngle
since it's 2d
Oh wait cause you take positions instead of directions for an angle calculation
You need to compare forward to the direction from one character to the other
I debug logged the player position and the grenade thrower position and they seem to log correctly
so their localScale.x do change
both of them
I didn't know that affected transform.position
I thought I could just get a raw angle from grenade thrower to player
Basically
var angle = Vector3.SignedAngle(Vector3.forward, player.transform.position - transform.position)
Huh that has nothing to do with scale
Vector2 final = new Vector2(Mathf.Cos(angle * Mathf.Deg2Rad), Mathf.Sin(angle * Mathf.Deg2Rad));
Debug.DrawRay(transform.position, final, Color.red);```
so I had to change Vector3.SignedAngle to Vector2 or it gave a red squiggle
and now the angle is always 0
Vector3 angle needs an axis I think
Im on my phone rn but try adding Vector3.up as a last Argument
angle is always 90 now
whatever z is it seems to constantly be that now
Vector2 final = new Vector2(Mathf.Cos(angle * Mathf.Deg2Rad), Mathf.Sin(angle * Mathf.Deg2Rad));
Debug.DrawRay(transform.position, final, Color.red);```
What do you mean whatever z is
How come you even need the angle for this? If you want to throw it at the player then the direction is just player.transform.position - transform.position.
using the angle would only be like if you wanted to see if the enemy had "vision" of the player
Oh, was so focused on fixing that Code that I didnt even think about that 😂
i believe that final value you have calculated should give you the same direction. Maybe something needed to be normalized, but yea no point really doing it anyways
cool thanks
oh actually, that final value would only work if this was aligned with the unit circle
Losing a project sucks, as Osteel mentioned because its on a physical location there might not be a way to recover it unless you have a backup somewhere else, if you do decide to try version control, I find GitHub or BitBucket as nice gits, with "SourceTree" or "GitHub for Desktop" to access your git quite nice too, since its on the cloud, youd be able to access your projects anywhere with internet this way, and revert backups in case you mess up a version of your working project you want to restore later
Is it common to get this _unity_self value cannot be null error and can i do something to fix it? It appears everytime I start the game while inspecting a SO instance. It doesnt happen if i start then click on an SO to inspect it. I dont have a custom inspector for it or anything. I assume its some corrupted data, because ive changed whats in this SO a few times (added/removed stuff)
Its not a major issue since i can avoid it, but just kinda annoying
what does this error means ?
empty animation event / missing methods
this seems like a unity editor bug
im aware it is, but i get it everytime when inspecting an SO and entering play mode
everything seems to be working fine but i have these errors
`private bool IsVisibleInScreen(Camera c, GameObject target)
{
var planes = GeometryUtility.CalculateFrustumPlanes(c);
var point = target.transform.position;
foreach (var plane in planes)
{
if (plane.GetDistanceToPoint(point) < PlayerController.instance.cameratest)
{
return false;
}
}
return true;
}`
Am I able to write this code as a job?
I'm having an issue because of the parameters that it needs to take in
You might be able to if you only use blittable types.
Another point is that the overhead is probably gonna make it less performant as a job.
Yeah, I'm not sure if it'd be worth it :/
if its a point anyway why not transform into viewport space and check if out of bounds?
is that supposed to not work?
I get:
ArgumentException: SceneManager.SetActiveScene failed; scene 'Mountains' is not loaded and therefore cannot be set active
but im waiting until scene is valid
Nvm
Anyone know a way to get the .exe path including the file name of the .exe? I tried GetModuleFileName with p/invoke but it is just giving me C:\Users
Exe path of what
Of the built game
I'm trying to restart the game from inside the game itself
Yeah I could use those, but I didn't know if there was something that would just give it to me in one go
Not sure that's possible
Since if you start a process from this process it'll be a child process, right?
Yeah maybe not, but I was gonna try to launch a launcher process that doesn't get killed by the parent process which will launch the game again
Call of duty does this when it updates or fails to connect to the internet so I just wanted to see if I could do something similar
That was the first thing I tried, but GetEntryAssembly returns null presumably because it's not a standard c# application.
I'm just surprised GetModuleFileName is giving me C:\Users, from what I've researched it's supposed to give the .exe path including the filename of the .exe.
I'll just have to use Application.dataPath and Application.productName for now.
Oh my god, GetModuleFileName was working, but I was using a UI toolkit label to display the string and for some unkown reason it was only displaying C:\Users
I logged it to the log and it is the full path. I don't get why UI Toolkit was truncating it
Lol I think it thinks it is a new line character because my user folder is C:\Users\natha
Lmfao
Oof
Big oof
As a fellow Nathan and C:\Users\natha owner, thanks for the heads up
How would I show a button "disabled" graphic without disabling the button?
I am trying to add speed settings for the game x1, x2, x5 and when you press 1 option, others would show as disabled/not active
myButton.IsInteractable = false
I believe it is button.interactable = false
But that prevents from clicking on the button
Is that not what you want?
oh for a button that works too you are right
Selected item would have different graphic.
wdym
If you want a radio button, just make it so when you click on the button, change the button text to an X, and then set the old active button text to empty.
you press x1, x1 button graphic becomes "active", but x2, x5 becomes "Deactivated"
I dont want to rename the button text
I want to change the graphic
Then change the Source Image
If you're wanting to change the image depending on its state, then you will need to change the Image 😑
If you're wanting to change the color then you just need to change the button.color variable
Buttons have 4 or 5 states that let you set different image for each state.
I am looking for a built in way
I dont want to set graphic in script
The only other way is to have all of the images already on gameobjects and enable/disable the gameobjects depending on the image you want active, but you shouldn't do that.
How do i make a gravity tool where you can pickup objects by having the script enabled and then pressing left mouse button to pick the object up and when you hold a object you can move it like its infront of you and rotate if you hold shift and move your mouse also you can move it forward and backwards using scroll wheel and if you press left mouse button you you place it with gravity and if you right click you place without gravity?? (I know this is hard)
@upper pilot What you're trying to do is very simple, there's no way to do it without scripting unless if Toggles does what you need it to do.
There is
I just cant find how to enable this.
yeah but you're in code general.
most of the convos in here belong there anyway
Yea ik
right, its called Toggle Group for some reason, not RadioButton group 😮
I think in here you're expected to have some sort of coding experience doing at least one of the things in your question
I'm really not sure then.
Yea i have ik i need to use a raycast and then idk what to use
manyyy pickup scripts on the internet to get started, its all about how you you tailor it to your usecase
oh i just got told that using others scripts are bad
its bad only if you are blindly copying
everyone in gamedev reuses scripts
oh yea i will read the code and understand what it does or ask my teacher
Ohh, RadioButton and RadioButtonGroup are not components, it looks like you need to use RadioButton radioButton = new() to use it. Its strange there isn't a component for it though.
I am using Toggle group and it does what I need
👍
Any idea on why this doesn't work
LayerMask layers = LayerMask.NameToLayer("Interactable") | LayerMask.NameToLayer("Object");
foreach (Transform obj in world.transform)
{
if(obj.gameObject.layer != layers)
obj.gameObject.SetActive(false);
}
If I only type one layer it works, but if i do more than one (2 in this case) it doesn't
It is because you're trying to compare one layer to multiple layers. Try this
LayerMask layers = LayerMask.GetMask("Interactable", "Object");
foreach (Transform obj in world.transform)
{
if ((layers & (1 << obj.gameObject.layer)) == 0)
obj.gameObject.SetActive(false);
}```
yh doesnt work either i have alredy tried
I have edited this, try this
that actually works tysm
If anyone is curious, I got my app restarter working. Here is the code,
Restarter app code:
// compiled with .NET 8 Native AOT
internal class Program
{
// first arg is processID
// second arg is process file path
static void Main(string[] args)
{
int processId = int.Parse(args[0]);
string processToStart = args[1];
while (true)
{
var processes = Process.GetProcesses();
if (!processes.Any(p => p.Id == processId))
break;
Thread.Sleep(100);
}
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = processToStart;
start.UseShellExecute = true;
Process.Start(start);
}
}
Code in Unity:
public static class AppRestarter
{
public static void Restart()
{
var currentProcess = System.Diagnostics.Process.GetCurrentProcess();
System.Diagnostics.ProcessStartInfo start =
new System.Diagnostics.ProcessStartInfo();
start.FileName = "restarter.exe";
start.Arguments = currentProcess.Id + " " + currentProcess.MainModule.FileName;
start.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; //Hides GUI
start.CreateNoWindow = true; //Hides console
start.UseShellExecute = false;
System.Diagnostics.Process.Start(start);
Application.Quit();
}
}
Does Unity loads the texture of any asset "mentioned" in the scene? Even if I have a prefab referenced in the scene Object, and no one instantiate it, it will still load it's textures to VRAM? How do I prevent it from loading everything in the scene?
Use addressables
Resource.Load or bundles
Anyone know how to fix this, what causes this?
here is the script that I use to make a player appear when he connects to the game, the only problem is that in certain cases the player who appears does not take the correct ID in his MyID variable which allows him to be differentiated from the other iterations of player, how can I ensure that the player that appears is indeed the ID that is intended for it, that is to say the ID that the script to detect as not assigning to an already existing clone?
the part of the script which makes the player appear (The script has the name CLIENT):
if (!ConnectedPlayer.Contains(NewID))
{
NewIterationID = NewID;
player = Instantiate(PlayerPrefab,new Vector3(0,1,0), Quaternion.identity);
Debug.LogError("NEW PLAYER ARRIVED : " + NewID);
ConnectedPlayer.Add(NewIterationID);
}
the part of the script present on the player and which is supposed to recover his ID (the script is called Ennemie):
void Start()
{
clientComponent = GameObject.Find("Player").GetComponent<CLIENT>();
MyID = clientComponent.NewIterationID;
Debug.LogError("Player : " + MyID +" has been sumoned");
}
for exemple Here 2 player connected into the game with 2 different ID but the 2 iteration take the same ID
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
is there a specific reason you had to do this in multiple channels ?
no sry
I just didnt see it in the others
Disable Camera and check if there is no other camera in scene
sorry, i posted by mistake here, and posted on the code begginer also. Is already solved :))
Silly issue, i havent got the eventsystem lmao
hey guys I couldn't really find information about this. I was wondering, if I have a bunch of references to a material, does that material get instantiated a bunch?
All the references should just be pointing to the material file right?
Correct, itll all point to your asset file at design time, and only create a new instance at runtime if "GPU Instancing" is enabled on the material AFAIK
you mean only if I apply that material to something, right?
Yeah, if a mesh or something references a material using "GPU Instancing", that mesh will have a new "material (Instance)", instead of directly pointing to the material - meaning changing the file material (for example, to a different color) will NOT affect instanced versions of it at runtime
well it's just that if you change properties on the .material at runtime, it will create a new instance
if you change properties on the .sharedMaterial, it will not create a new instance and instead change the properties on the shared material
I reread the rules and I still wasn't for sure on where questions can be asked and if all questions pretaining to unity must go through dots form.
don't crosspost
the using UnityEngine;
public class MoveSpriteUp : MonoBehaviour
{
public float MoveSpeed;
void Update()
{
transform.position += transform.up * MoveSpeed *
10 * Time.deltaTime;
}
}
for vr
Ok
Is there any way to stop player in Air if player click button in opposite direction? Im using RigidbodyFirstPersonController from standard assets
arent the standard assets really old? i would assume these arent build to be completely modular, so you would have the most control while making your own movement controller
But it works fine
🤷♂️ i cant even find the script online, but theres really only one answer to your question. Yes it is possible, you just have to code it

private void FixedUpdate()
{
GroundCheck();
Vector2 input = GetInput();
if ((Mathf.Abs(input.x) > float.Epsilon || Mathf.Abs(input.y) > float.Epsilon) && (/*advancedSettings.airControl ||*/ m_IsGrounded))
{
Vector3 desiredMove = transform.forward * input.y + transform.right * input.x;
desiredMove = Vector3.ProjectOnPlane(desiredMove, m_GroundContactNormal).normalized;
FS.currentStepLenght = movementSettings.CurrentTargetSpeed / running;
FS.PlayStepSounds();
if (Running)
Walking = false;
else
Walking = true;
desiredMove = desiredMove * movementSettings.CurrentTargetSpeed;
if (m_RigidBody.velocity.sqrMagnitude < (movementSettings.CurrentTargetSpeed * movementSettings.CurrentTargetSpeed))
m_RigidBody.AddForce(desiredMove * SlopeMultiplier(), ForceMode.Impulse);
}
else
{
movementSettings.m_Running = false;
Walking = false;
}
}
i think its only needed to make this 🤔
!code itll be formatted nicely with this
📃 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.
'''cs
backticks not quotes, also what do you mean "stop player in Air if player click button in opposite direction". do you want them completely frozen in air?
yes
if you want the opposite direction of movement, i guess you could check the angle between desiredMove and the current velocity. then stopping it air depends on how u want the game to feel. You can make it kinematic but it wont respond to forces
test
{
GroundCheck();
Vector2 input = GetInput();
if ((Mathf.Abs(input.x) > float.Epsilon || Mathf.Abs(input.y) > float.Epsilon) && (/*advancedSettings.airControl ||*/ m_IsGrounded))
{
Vector3 desiredMove = transform.forward * input.y + transform.right * input.x;
desiredMove = Vector3.ProjectOnPlane(desiredMove, m_GroundContactNormal).normalized;
FS.currentStepLenght = movementSettings.CurrentTargetSpeed / running;
FS.PlayStepSounds();
if (Running)
Walking = false;
else
Walking = true;
desiredMove = desiredMove * movementSettings.CurrentTargetSpeed;
if (m_RigidBody.velocity.sqrMagnitude < (movementSettings.CurrentTargetSpeed * movementSettings.CurrentTargetSpeed))
m_RigidBody.AddForce(desiredMove * SlopeMultiplier(), ForceMode.Impulse);
}
else
{
movementSettings.m_Running = false;
Walking = false;
}
} ```
read my message above this, theres probably more to consider like
how long do you want the player stopped for, should they eventually start moving in the direction of input?
you may need to ignore the y velocity when checking the opposite direction as well
Im honestly unsure if the velocity can be reliably used even, because with rigidbodies it may slide up/down slopes causing it to not be what you expect
it should be fine to just use the velocity (without the y component) normalized
I wanna make it work like in tf2
then you'd probably want to look at guides which replicate source movement. i havent played tf2 in awhile but im pretty sure you dont just stop in midair in that game, which you initially described.
Given your response, I dont really think you've understood any of what i wrote above. I think you should ditch this old code you're using and just follow a tutorial online
I mean only x and z
Hello, i'm trying to achive a swiming movement so i made the character move with rigidbody, and the bouncy effect script uses rigidbody too, the problem here is when the charater moves the bouncy stops till the character stops, any idea how to solve this?
What are some ways you guys limit the amount of database writes in order to limit server costs? For instance, I keep track of statistics for the player and I want to store these stats in a database, but obviously it would get pretty expensive to update the database everytime a stat increases since these will increase very often in my game.
hey guys im trying to get time diffrence betwean a saved time and current time but the numbers are super big and it drops lesser numbers and i aways get a resault of 0. can someone help me?
Hello I have a question, I want to have a struct or class alter the visual representation in the inspector oppn changing an enum. Besides making a custom inspector.
I have a struct called submission paper that has a list of type Answer.
Currently I have them as structs
Example of what I want.
unfortunately the default way is to make a custom inspector
otherwise go grab naughtyattributes off github
Thats not possible to do like that. Float cannot hold all of that data.
Why not just save the string??
PS: player prefs is not a good place to store game data as its easily modifiable by the user. ("hacked")
Yeah save the entire DateTime as string, and DateTime.Parse() it back when loading.
Then you can subtract two DateTime and it'll give you a TimeSpan object, from which you can access seconds, minutes, days, etc.
^^this or save Ticks
Heya, I'm trying to do some procedural world generation using noise and meshes etc. I've just been trying to implement LOD into it but my triangles seem to be weirdly messing up towards the end of the iterations. My code is pretty simple but here's the problem:
private int[] calculateTriangles() {
// Generate triangles
int[] triangles = new int[(WorldGeneration.chunk_vertex_length - 1) * (WorldGeneration.chunk_vertex_length - 1) * 6];
int count = 0;
for (int x = 0; x < 252; x++) { // Should be [x < WorldGeneration.chunk_vertex_length - 1] - its not atm just for debugging
for (int z = 0; z < WorldGeneration.chunk_vertex_length - 1; z++) {
int baseIndex = z + x * WorldGeneration.chunk_vertex_length;
// Just some debug code here
if(x == 251) {
if (z == 15) Debug.Log(baseIndex);
if (z > 15) continue;
}
// First triangle
triangles[count] = baseIndex;
triangles[count + 1] = baseIndex + 1;
triangles[count + 2] = baseIndex + WorldGeneration.chunk_vertex_length;
// Second triangle
triangles[count + 3] = baseIndex + 1;
triangles[count + 4] = baseIndex + WorldGeneration.chunk_vertex_length + 1;
triangles[count + 5] = baseIndex + WorldGeneration.chunk_vertex_length;
count += 6; // Move to the next set of triangles
}
}
return triangles;
}
Thanks very much for any help ❤️ (this has been killing me all day)
I could only guess some floating point precision problems. I'd try to log a list of position (probably easier to write to text) and compare values
can you write some examplery code, im getting the approach but some code doesnt show
Shouldn't be - chunk_vertex_length is an int
Sure thing
// convert
string str = DateTime.Now.ToString("s");
// convert back
DateTime dt = DateTime.Parse(str);
The "s" format specifier formats the date in a way that is standardized, so anyone around the world will be able to convert it back to a DateTime.
It produces a string like 2023-12-03T15:48:35
i see
Consider using a DateTimeOffset instead, so time zone information is preserved when saving/loading. In that case, use the "o" format string
Oh, huh. Looks like what you have there is pretty standard otherwise.
//Indices
for (int x = 0; x < rows - 1; x++)
{
for (int z = 0; z < columns - 1; z++)
{
int offset = z + (x * columns);
glm::vec3 tri1 = glm::vec3(offset, offset + columns, offset + columns + 1);
render.indices.push_back(offset);
render.indices.push_back(offset + columns);
render.indices.push_back(offset + columns + 1);
glm::vec3 tri2 = glm::vec3(offset, offset + 1, offset + columns + 1);
render.indices.push_back(offset);
render.indices.push_back(offset + 1);
render.indices.push_back(offset + columns + 1);
//std::cout << tri1.x << ", " << tri1.y << ", " << tri1.z << " ~~ " << tri2.x << ", " << tri2.y << ", " << tri2.z << std::endl;
}
}```
This is pretty much what I do in OpenGL
Hmm that's really strange, it literally just gets to one point and then the triangles from there go back to (0,0) on the mesh
This part looks ok to me, maybe the problem is with your vertex order or something
I suggest using something like Handles.Label in OnDrawGizmos or in a custom editor to draw the vertex indices on screen
And maybe triangle indices (divided by 3) in the center of each triangle
Shouldn't be - I'm iterating the same way pretty much
for (int x = 0; x < WorldGeneration.chunk_vertex_length; x++) {
for (int z = 0; z < WorldGeneration.chunk_vertex_length; z++) {
float x_pos = x / (float)worldGen_script.lod;
float z_pos = z / (float)worldGen_script.lod;
I'll give it a go debugging with gizmos tho
I don't see you accounting for LOD anywhere but the vertex positions. Shouldn't it affect the vertex count too?
chunk_vertex_length = (chunk_size + 1) * lod;
rather, you're doing division to a float*
for a position so again with the precision problem of my previous post
Even if there is a problem there it should only effect the position of the vertex slightly right? In that case it shouldn't make a difference for the triangles as I'm just referencing their indexes
I'm just observing from the picture it feels less like an algorithm problem and more of a whoops the next value truncated into a wrong value
That's true
This is still my go-to step 1, visualize your data
I'll start with that thanks
I need some help with my camera I have a camera that rotates around the player showed in the video but lets say i only want to rotate it behind the player and when it hits the side it stops. Rn it hits the side but then i cant move it anymore
Heres my code
https://gdl.space/sepocapafa.cs
anyone know of a way to optimize onTriggerStay or some alternative? I only need to check for one collision between objects but objects sometimes get instantiated already in contact with others, so onTriggerEnter doesn't work, but onTrigger stay is way too unoptimized
!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.
also use mp4 for videos embed
yes use actual physics queries
like overlap or alike
also you can use coroutine to make your own intervals if you don't want to do it every Update
thanks! Figured there was some way in the engine to do what I wanted but didnt know what to look for.
dang..I would use cinemachine orbital camera 🧈
though you'd still need code for the second part
i will try thx
Can you help me limit the rotation i am now using cinemachine?
are you using orbital ? if you expand the panel they have fields for that now
I am using orbital this is my camera inspector
oh thx
I had a 2d grid map, but it has no heights.
How can i make the map have hills just as these?
Either prefab a custom mesh, or if you want to apply different vertex compositions then you need to modify them directly through their vertices
I see, I wanted to avoid adding extra vertices due to performanc reasons, is there really no other way?
I had considered tesseleation and height maps, but I combine meshes of similar materials together so that is a bit difficult to pull off
no one says you have to add extra verts. Use what you got and move em around (well, assuming your hexagon mesh isnt composed of the absolute minimal verts)
it is, but your right, this probably the best way to go. Thanks
I am using the right one, with 4 triangles
You can do so much more with a few more verts with miniscule performance changes. That and you've got tools like culling so it shouldn't be an issue when it comes to optimizing.
how many verts would you recommend per hex?
If you make yourself the script to create the meshes, your alg will adjust it via values so it comes down to testing what you want later on
That's usually how it goes for the most part anyway
would be odd to hard code vert values when it comes to primitives, but I guess you can argue that's exactly how'd you go about making a quad ;p
what are primitives?
primitive shapes
ahh
stuff that's usually easy to subdivide
lastly, is there a max vert count, I probably should go past?
there is in unity, but it's per mesh and you're not likely to hit that unless you're doing chunks
(which is something else to consider)
I am using chunks right now, definetely increase performance since I can disable those that arent in view
why cant i add functions/methods to my custom network manager and call them from other scripts?
this is in my custom network manager
Seems like CustomNetworkManager.Singleton returns a value of type NetworkManager, not CustomNetworkManager
You'd need to modify the definition of the Singleton property, or cast the value every time you need to access members on CustomNetworkManager:
((CustomNetworkManager)CustomNetworkManager.Singleton).test();
Ah
Prefer the first (modify the definition) if possible
Is there anyway I can modify the definition of the Singleton property without modifying the original NetworkManager?
Good question, never used that. Probably not, since it's static
Overrides are out of the question
What if I just made a new singleton in my Custom class and called it something like Instance instead of singleton
You could make a SEPARATE static variable probably?
Call it Instance to avoid... ah
Yup lol
Yeah possible
Instance => (CustomNetworkManager)Singleton;
Or marking the property with new? Can you do that on static stuff?
If I do this, do I also need to set the instance variable inside the awake function of my custom network manager?
Probably not, if it already works without. This is a computed read-only property that just gets the value and casts it
This works, you can completely shadow it with the following
public static new CustomNetworkManager Singleton => (CustomNetworkManager)NetworkManager.Singleton;
Hi all, I've got an abstract RuntimeSet<T>:ScriptableObject class, and a TeamableRuntimeSet:RuntimeSet<Teamable> class, where Teamable: MonoBehaviour
When I serialize a field of RuntimeSet<MonoBehaviour> I expect RuntimeSets of classes that extend Monobehaviour to show up, and the TeamableRuntimeSet scriptable objects do show up, but I can't drag/select them into the field, I couldn't really find anything on it so I was wondering if someone here knows about this issue
My understanding is that unity doesn't support serialized abstract classes out of the box and you need to do some [SerializeRerefence] shenannies and do your own editor drawing
Found this thread re Unity 2020 but I don't know the latest info, so maybe my info is outdated: https://forum.unity.com/threads/serializereference-genericserializedreferenceinspectorui.813366/
Project now should be accessed from github page. GitHub repository :
https://github.com/TextusGames/UnitySerializedReferenceUI
I have made generic...
oh great tysm I think that's it, going to do that now
Reproduced your code architecture, it's not possible to do that in C# so Unity won't be able to do it eitther
Cannot implicitly convert type 'TeamableRuntimeSet' to 'RuntimeSet<MonoBehaviour>'
his RuntimeSet<T> is abstract and inherits from SO fwiw
oh sorry, you were saying you were trying that in c#
You'd have to dive into type parameter variance to achieve that, which involves using interfaces, and Unity doesn't support that either lol
I'd utilize the adapter pattern if you're fixed on polymorphism of your underlying c# classes.. have your classes be their own thing (unrelated to MBs and SOs) and then have MBs and/or SOs to wrap them
I'm actually pretty far into a project that's doing the polymorphism thing and.. I keep the polymorphism away from unity
Yeah it was not made for polymorphism, but more for composition and other design patterns
ahhh gotcha, adapter seems pretty straightforward, ty!
https://pastebin.com/jeKKxXuR that's how I'm doing it
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
it's a tile based game.. but in unity i .. don't want to have the inspector/editor have to figure out too much, so I just manually have an initalize method that I call programmatically and pass it whatever, and it can figure out what to init/display accordingly
then all my behaviour management is stuff like "if tile is IMoveable, move it" or "if tile is IDestroyable, destroy it" or whatever
every specific tile inherits from the abstract parent class and just gets all the default behaviour (like a constructor that sets the id, location on the grid, etc) and it just implements the "tile-type specific" behaviour.. like maybe one tile moves erratically or not at all each turn, maybe another can only be destroyed by another certain tile type, etc
a lot of the stuff I have already depends on serialized stuff i.e. an enemy has an Teamable:MonoBehaviour, ITeamable component plus a couple other to manage health/pathfinding/alerts so I'm not sure i could make it work without a bunch of refactoring but that sounds interesting, probably keep it in mind for after the semester
I'm trying to make a slippery floor on one of my tilemaps so that everything placed by the tilemap should be slippery. It doesn't work, I've already tried to work with materials that have 0 friction, it doesn't work and I've already tried to code it with the help of the internet but no matter how I code it, either everything is slippery or it doesn't slip at all. Is there an example code I can use or a component I can use?
I want to have a transform stop moving when it hits a wall or something is in front of it, should i use a raycast or boxcast in this situation? It could be like a leaping dog.
Either works. Depends what shape you want the cast to be. They both do the same thing after that.
easy, put the slippery tiles in a separate tilemap
so you only deal with their collider/physics material separate
not sure anything else is code related
Hi all. im a little confused. As far as i understand, animations triggers fire off, then get disabled until they're fired again. However, in this case that doesnt seem to happen:
- it doesnt seem to transition through any of the triggers (i hooked the dash animations to
any statewih the corresponding trigger param as their sole condition) - dash end seems to trigger 24/7 even hen not dashing
Does anyone know why?
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.
didnt wanna omit info that might be helpful lol..
As far as I know I have 2 tile maps in the same grid. It should work or does it being in the same grid change something?
its okay but you need to split it a bit more cause its hard to read at a glance
coming from regular software dev to this is surprisingly difficult, im not even rlly aware whats wrong
hmm maybe
I would debug the animator first
select the object that has the animator in playmode you should be able to see if trigger stays on or not
you can have many tilemaps in one grid it doesn't matter, but each tilemap has diff purpose so they ca be split to more if needed
except dash end
i just saw the time tho, ill have to take time for it tmrw
its almost 2 am 💀
lol for me too.
I’ll tomorrow write here again about it. I think they are separate tile maps so it should work
ohh ok thought you tried it
General question, is there a simple function to static batch objects that are instantiated? I have larger objects that spawn later and they aren't being batched
Is there a nice way to get (deterministic) random points on a certain NavMeshSurface? Currently im using NavMesh.CalculateTriangulation();, then get a random vertex, and then NavMesh.SamplePosition. but it appears that the triangulation itself is not deterministic when there are multiple surfaces. It seems to just cycle between a few different possible lists.
I was thinking of some options:
- generate the list once while only having 1 surface active, store that result on some script in every scene. This seems quite tedious though if i want to make changes
- make a script on some GO which acts as spawn points, manually input some bounds, then randomly choose a point and sample the position onto the navmesh. Seems better but then ill have to make the sample position maxDistance large enough to account for any bounds.
Just looking to see if anyone has thoughts about what I should do
They are seperated and doesnt matter what I do I cant get the slippery effect.
I tried different codes and they dont work. Im tryng to make a script that I add to my slipperyTile and Im tryng avoid to much change and adding of stuff in my player controls script. Can u help me make some code for the Slipperyeffect? (im new to unity and programming idk if I should have written this in Code beginner)
What player controller are you using?
I don't need to worry about Time.delta time when I'm using physics like: rb.AddForce(Vector2.up * ampSpeed, ForceMode2D.Force); right?
the AddForce equations already consider delta time if they need it
I don’t know if player controller is the right name, I made the controls myself. I made like most probably do(with Tutorials/Internet) the controls with vector. I made that you only jump when there’s a ground under you and I added coyote jumping also(jump still possible for a short time after touching edge of platform) also I added with tutorials Jump higher function when u hold and shorter when u just tab quickly. I put also the animation and sounds in controls code. I also gave my player 0 friction bc I saw in a video it stops the player from getting stuck when u jump and run against a wall.
I don’t know if any of that stuff influences slippery tilemap I wanna add.
It depends on how your character moves already as there's many different ways.
I copied those vector lines from tutorials I don’t fully understand it. Should I paste it in here?
Wait a min
private void Update()
{
dirX = Input.GetAxisRaw("Horizontal");
if (Input.GetButtonDown("Jump"))
{
jumpBufferCounter = jumpBufferTime;
}
else
{
jumpBufferCounter -= Time.deltaTime;
}
if (coyoteTimeCounter > 0f && Input.GetButtonDown("Jump"))
{
jumpSoundEffect.Play();
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
coyoteTimeCounter = 0f;
jumpBufferCounter = 0f;
}
if (IsGrounded())
{
coyoteTimeCounter = coyoteTime;
}
else
{
coyoteTimeCounter -= Time.deltaTime;
}
if (Input.GetButtonUp("Jump") && rb.velocity.y > 0f)
{
rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f);
coyoteTimeCounter = 0f;
}
UpdateAnimationState();
this are the controls and the next method is where the animations are handled
wanna see that too or is here maybe the root of the problem?
forgot this private bool IsGrounded()
{
return Physics2D.CapsuleCast(coll.bounds.center, coll.bounds.size, CapsuleDirection2D.Vertical, 0f, Vector2.down, .1f, jumpableGround);
}
So you have a rigidbody controller. These are perfect for physics interactions.
for sharing code here:
!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.
Oh sry didn’t know about that
Ahh that’s what you meant with what controller. Didn’t know people use something other than a Rigidbody
I see nothing that sets your X velocity
it's declared as dirX but I see no instances of it
I'm going to assume if physical materials don't work, that there's code somewhere that dictates if grounded + not "holding A or D" velocity is set to 0.
Ctrl+F and highlight everything that mentions "dirX" and have a look
This is where the fun of making something both slide and stop on slopes comes in
Well I’m right now not home. Can we continue this conversation later? I will take look into my code when im back home. I may have made code that influence the material of the player maybe.
i cant ask for help?
help, yes.
pay someone to do it for you, 🤔
i can find a way to do it
i have been struggling for weeks and stressing and i gave up
The server doesn't do job offers. Try the links provided #archived-code-general message
the link doesnt do anything
!collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
These are the links.
hey so im trying to check if the camera can see the player or not and i use a raycast. now even though the player is behind a wall the camera still returns true... is there something im doing wrong here?
You're casting the ray with playerMask
yes?
that means the ray will collide with only the player and not the walls
thats the point
you'd need to add walls to the layermask and then a separate check for if the object it hits is the player
oh waIit so it will ignore the walls?
aah okay
thanks
you can use this same strat to add glass to a separate layer that is not on the cameras layermask so the beam will ignore glass and detect you
Can someone help with making a parallax? I'm trying to use Dani's tutorial, but i cant get the objects to reappear, once gone off the screen.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Parallex : MonoBehaviour {
private float length, startPos;
public GameObject cam;
public float parallexEffect;
void Start () {
startPos = transform.position.x;
length = GetComponent<SpriteRenderer>().bounds.size.x;
}
void FixedUpdate () {
float temp = (cam.transform.position.x * (1-parallexEffect));
float dist = (cam.transform.position.x*parallexEffect);
transform.position = new Vector3(startPos + dist, transform.position.y, transform.position.z);
if (temp > startPos + length) startPos += length;
else if (temp < startPos - length) startPos -= length;
}
}
I think its because i dont have the object in the sprite renderer,
its like this instead
Ok so this is what I got, I basically want the ship to play a different animation if it is moving perpendicular and in a certain direction from its current orientation as the digram shows. Not sure how to setup the math to get this working.
Good morning, hope all is well. Is there anyone who is good with the Slider control in the UI? I have 2, one for music, one for sfx. Audio Mixer works fine so the sounds are there but the sliders do not reflect the volumes. Not sure if anyone can assist in #📲┃ui-ux or not.
You can compare its forward direction with its velocity
For example, Vector3.Dot(transform.forward, rb.velocity.normalized)
Or Vector3.Angle
If it's 2D then you probably need to use transform.right/up instead of forward
With dot, moving sideways will give you 0
Backwards will give you -1, forwards is 1
Volume sliders need to be logarithmic, because our sense of loudness is logarithmic.
I posted the entire thing in #📲┃ui-ux if you can check it out, I appreciate it.
Also its a 2d game so doesnt need crazy things
What's the standard practice for teleporting a rigidbody with interpolation?
Interpolated teleporting?
So flying?
usually lerp timedeltatime if it's what i think you're asking
rb.MovePosition
Sorry let me rephrase that. The interpolation setting on the rigidbody is set to Interpolate, which smooths the movement across frame updates.
I just want to teleport the object to some new location.
Effectively ignoring interpolation for that movement.
like Praetor said
Rigidbody.MovePosition moves a Rigidbody and complies with the interpolation settings.
But I don't want this.
Teleporting a Rigidbody from one position to another uses Rigidbody.position instead of MovePosition.
alright then
The transform will be updated after the next physics simulation step. That's kind of a pain.
Kinda wish setting the transform would just... disable interpolation for that frame.
setting rigidbody position is very useful
it’s like moving the transform, but all the colliders and rb internals get updated
You said you wanted interpolation
If you don't, then just use RB.position
why can structs not inherit?
They go into detail here
It's essentially to do with value types in .NET
Because pointers are always the same size but copying by value is impossible without knowing the exact size of the thing to copy
structs can inherit interfaces tough
implement, not inherit
yeah my bad
i just imagine the compiler could just try to define a value type of a child struct by getting together all the methods/fields, and creating the structure for the child value type
but i guess that just isn’t how it works
Yeah but when you pass it as a parameter to a function the function needs to know how big everything is to organize the stack frame. Not possible with variable sized parameters
No inheritance means the memory size of the struct is known at compile time
that makes sense if you have a class inheritting from a struct, but if you have a struct inheritting from a struct, then the compiler should be able to figure out the size of a derived struct. it would be a compile-time const
There's a version of physics2d.raycast that returns a raycasthit2d. How is this meant to be used in order to check whether or not there was an actual hit?
See if the transform contained is null?
sizeof(Child) = sizeof(Parent) + sizeof(Child’s fields)
The same function can be called with differently sizes structures though
Which won't be possible
“This function returns a RaycastHit2D object with a reference to the Collider that is hit by the ray (the Collider property of the result will be NULL if nothing was hit). “
Ah, thank you. They could have added a convenience property
you don’t usually want to use Raycast tho, imo. It is more common to use one of the nonalloc methods that grabs an array to populate a collection. this way you can sift through/filter results
those methods return an int as the number of hits
are they ordered ?
no
if you output to a list, you can sort the list based on whatever criterion
such as by distance
👍
oh, i think i see the issue now
ty
btw, you probably also want to know about Collider2D.Cast
the cost for a single boxcollider .Cast is almost the same as a single Raycast call
Can someone explain this error?
For context, I'm trying to mod a game by replacing the player model
We ask that you do not:
• Directly discuss modding or decompiling.
read the community conduct
Hello - I have a game published to Android + iOS but for some reason my iOS version makes users restore purchases each time they open the app. I'm trying to figure out why this is and would love some feedback on my In App Purchases (IAP) layout. There's only one IAP which is a full game upgrade. Thank you!
I have a world that I'm trying to render in isometric, blending 3D and 2D. I found using the camera at an isometric angle introduces a lot of pixel jitter and other subpixel issues due to the math of the camera being rotated. One solution I have found is rotating the world itself fixes every single issue I have, keeping all the objects on a nice, aligned, 2D plane for the final render. The only concern with this is that it makes workflow pretty unintuitive since the engine is obviously not designed for worlds to be rotated. What would be the best way to rotate the entire world(in this case a nest of GameObjects all under a single "Terrain" parent object) in a way that is only visual, during runtime? Methods I've tried:
- RenderPipelineManager.beginCameraRendering and rotating the gameObject during render and then undoing the rotation at RenderPipelineManager.endCameraRendering. This has gameplay implications though as it rotates the entities around they don't always end up in the same position in the world as their pre-rotated counterpart. Using a navmesh for example, a character may be at the top of the stairs in the editor but during runtime as the object tries to find itself among the navmesh, snaps it to the bottom of the stairs.
- Shaders. I know shaders don't have any effect on things at a gameplay level, but I'm not sure how to rotate an entire nest of objects on the same pivot(aka keeping the whole world together as it rotates) since all the objects will just rotate around their own pivot instead of their parents.
Any advice would be greatly appreciated
pixel jitter
are you saying you are trying to render 2d pixel art in an isometric world
2d pixel art in a 3d isometric world
there is an asset called Ultimate Isometric Toolkit which includes a simple sprite material to orient the sprites towards the camera and pixel-align them
which is all you need. you should definitely lay out your world naturalistically in the xz plane, and orient your camera in the projection you need (isometric, although you probably mean dimetric 2 x 1)
I have the sprites orienting fine, but if the camera is not perpendicular to an axis it introduces a ton of jitter that I have not found any asset able to resolve
are you trying to use the pixel perfect 2d script from unity?
the asset i am discussing resolves pixel alignment issues in the absence of pixel perfect 2d, which you cannot use
for a non-orthonormal projection
I've tried the pixel perfect camera, I've tried a few assets that are supposed to do it. While they all alleviate the jitter to a degree it's never to the precision I need
i am saying you cannot use it
I said I've tried it, not that I'm using it
gotchya
well that's all you have to do. the asset is $30. you shouldn't do any of the stuff you are discussing, although you could try authoring the shader it uses
https://assetstore.unity.com/packages/vfx/shaders/fullscreen-camera-effects/propixelizer-177877 is another one that I've used because it also has specific scripts to fix pixel jitter in 3d
this is coming from someone who makes a dimetric pixel art game
and it helps, but it's still there, just less so
do you have a screenshot of you game?
unfortunately under an NDA so I can't post much about it
the problem you are describing cannot be solved in a general way
which is perhaps valuable to know
however, you don't need jitter at all
well like I said, rotating the world solves everything. I just can't figure out how to rotate it in a way that does not effect the game
because you don't need to enforce alignment
you know, go ahead and do that then
I just can't figure out how to rotate it in a way that does not effect the game
so you see what i mean by not general
shaders seem like the go to but I can't seem to rotate entire nests of game objects around a single pivot
can you show me an example of a commercial shipping isometric pixel art game built in unity that lays out the world naturalistically in 3d and attempts to align every art pixel exactly to a canvas pixel?
you will not be able to find one
my suggestion is to not do that, because no one will notice
also can you link this because I'm not finding anything by that exact name
it cannot be done in a general way. however, the ultimate isometric toolkit does it 95%
unfortunately it looks like it's gone... 😦 https://code-beans.github.io/Ultimate-Isometric-Toolkit-Docs-and-Issue-Tracker/
I'll get a screenshot once I swap out sprites
annoying unity gets hung up in the package manager all the time now
so let me explain why this cannot be solved in a general way
for starters, this can't be solved in a general way with an ordinary orthonormal pixel art game either
the problem is just a lot less pronounced
as long as you want to do something in floating point and that's moving, like physics, a general approach has to have an answer for how to align a piece of art to the screen in a way that interacts correctly with another piece of art. if things can have non-integral speeds with respect to screen space, which is always for dimetric projections and frequent for ordinary orthonormal projections, you will have one of jitter, stretching, or irregular pacing
you don't see pixel alignment issues in retro games, but they have all painstakingly eliminating movement pacing issues, primarily by not using naturalistic physics at all
you can't have no issues because, you know, the rules for Ideal Pixel Art world can't be reconciled with naturalistic physics
do you know what i mean by irregular pacing? like characters have to move an integral amount every frame to appear to be moving smoothly with constant velocity, but with naturalistic physics, a speed of 2.5 pixels per frame means sometimes it moves 2 pixels, and sometimes it moves 3. it's just that with a dimetric project, it is always moving a non-integer number of pixel art canvas pixels per frame, whereas with ordinary 2d projection, you can control it
the issue is that in 2D you can easily round floating values for precision. But because of the math involved with a rotated camera you can't just round stuff. As you walk around, sprites get rounded at different alignments to your character/camera due to depth/rotational math etc
what people do is they do not align to the pixel art canvas while objects are moving, which includes when the camera is moving, so the answer is sort of that they don't stress too much about alignment at all
yeah i agree with you there is no general way
so even snapping things into position in screen space doesn't really matter because things like this:
you should not try to align generally
i think this looks good
it doesn't look good though, none of the pixels are aligned and as you move, due to this, everything wiggles
don't try to align while things move
that's why rotating the world works so well, I just need to find a way to rotate it with a shader
which means don't try to align
teenage mutant ninja turtles 🐢 the game
i think you are on the start of a long journey, and maybe you will arrive at the same place i did
do you understand what i am saying about movement pacing?
well I've been messing with this for half a year
here is a view with the camera rotated
yes, that is what i mean by movement pacing issues
it doesn't matter how the world is rotated
if you rotate your world, as you're describing
and in order to not have movement pacing
you will have to use different physics altogether
you will still have these problems with 2d sprite physics
because the underlying issue is that there's no general way to reconcile a non-integral amount of motion per frame with an aligned pixel art canvas
you have to choose your demon: either you have movement pacing, jitter or non-natural physics
imo, do not align
you don't need to align
nobody notices alignment issues
this is very noticable
even Ubisoft releases games with animations jumping between 30 and 60 fps
here is the world rotated
it's noticeable to you because you made it
and here is the final render
it's the same with every artist and their work. it's the drive for perfection
perfection is not ascertainable
okay well you see what i mean by movement pacing issues