#archived-code-general
1 messages ยท Page 387 of 1
hi, suppose i have a list and i want to remove some specific elements by index(such as index 1,3,4 etc) from the list, what should i do? a for loop return error in this case
and if you need to remove more than one remember to do it in reverse order starting from the highest index
thank you
Hey all, having a weird issue with serializing to file. I've created a really simplified code snippet and it even failed with the message: UnauthorizedAccessException: Access to the path is denied. I googled it and it said it could be an issue with my Windows permissions so I did a complete reset and the problem still persists. I've put all the 3 code files into a codeshare, any help appreciated! https://codeshare.io/g8Pp6V
you are supplying a path but no file name
guys my (gamecanva) does not show the elements inside it (it was fine) any one has similar issue
when i click on the canva it show me where the camera is
which gameobject contains that border image?
background canvas
so you have 2 canvas's active at the same time?
yes
one for background and the other 3 canvas one of them will be active depend on the situation
you should use Panels for that, not seperate canvas's
panels
let me read about it then
so each panel can have is it buttons images
and from the script i can show and hide another right?
correct
that is strange so when we use multiple canvas?
when you use world space canvas's
huh
do you have examples of that
or you can explain it in more details if you don't mind
say you have 2 characters in the scene and each has it's own dialog or stats canvas. Then you would make a world space canvas for each character
you mean like split screen
so each screen is a canva?
can i ask a question here?
no, a world space canvas exists in the world, not in the screen. So it can be any size and anywhere
!ask. Read the bot message
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #๐โfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
I have a problem in Unity where my BalanceUI script is not being found in my ScoreManager script. I'm using FindObjectOfType<BalanceUI>() to locate the BalanceUI object, but it's returning null. Any suggestions would be greatly appreciated!
And where do you use BalanceUI there?
1- the code you've provided (as Steve says) doesn't mention BalanceUI at all
2- if FindObjectOfType<BalanceUI>() is null, then the object isn't being found in the scene -> either you've not got one in the scene, or it is inactive
so i meant CashUI not balance mybad
yes it is inactive, but the code worked fine for my playerStats and it is also inactive
thats my code for playerstatsText
read the docs. There is an option to include inactive objects
im sorry its my first game, so im a beginner
then you should spend more time reading the docs not less
but im curious why does it work fine with my PlayerStats?
what object is PlayerStats on? Player?
no the script is on the inactive PlayerStatsText its just to display the current stats of the player
then you probably have duplicates in your scene so you should debug which PlayerStats has been found
this isn't showing the same situation as CashUI.
That GetComponent<TMP_Text>() is called on Awake().. which is called after you make this object active.
ahh
yeah, where is the FindObjectOfType<PlayerStats> ?
in my PlayerMovement Script and PlayerShooting Script, where i declare the speed and firerate
And which object are those scripts on
ahh maybe i know the problem now
Could the problem be that I am trying to continuously update my balance, which is inactive? Would it be possible to synchronize the score with the balance when I press P and open my upgrade panel?
i solved the problem, thank u !
you really need to look at your use of Find and Get because I'm sure that 99% of them are not needed
Maybe I should post this in another thread?
I'm trying to debug a Behavior Subgraph. I can select the Behavior Agent to debug in the main Behavior Graph, and that works fine. It shows that the main graph is currently inside the subgraph, but debugging doesn't show any activity inside the subgraph, and I can't select any agents there for debugging.
If I add another Behavior Agent script to the GameObject and attach the subgraph directly, I can enable debugging on that agent, and it works. However, it doesn't seem correct to use multiple Behavior Agent scripts on a single GameObject.
How can I properly debug a subgraph? Or is it correct to use multiple Behavior Agent scripts if you use multiple Behavior Graphs?
Anyone has experience with using Aron Granberg's A* Pathfinding package? I am wondering if anyone got a similar issue as me before where .reachedDestination seems to always be false despite being at the destination transform
we do not supply support for 3rd party assets. Contact the publisher
I understand that its not directly Unity related and hence isn't something people are to help out with but I was hoping someone had a similar experience and knows what's wrong because the official Discord for the 3rd Party Package does not really help me out
Just hoping someone happened to have a similar issue and know why it is so
have you read this? https://arongranberg.com/astar/docs/iastarai.html#reachedDestination
I'm making a fighting game in Unity and I'm working on the input buffer for it. With this I can dynamically create new special moves and perform them, and also images corresponding to button presses show up on screen for a more visual representation. Everything's working correctly so far except diagonals inputs don't read at all as there are images for when you input diagonals like down-left and down-right etc so that i can do proper motion inputs. I added a debug log to check whether it is actually being processed an no nothing's happening at all. Here's the script: https://pastebin.com/fqj0NYCu
HandleInput() is working correctly but HandleDiagonalInput() isn't working at all
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.
yep
yeah its quite tricky
How i can get an LocalizedAsset in a Specific Locale?
Hi guys, is anyone else having issues with unity Version control? My token keeps expiring, I have been unable to commit my code for a really long time, and I cannot find a fix for this
ez fix https://git-scm.com/
!logs
Could also try the dedicated Plastic SCM UI
or the ez fix navarone suggested ๐
#๐ปโunity-talk for further Unity Version Control troubleshooting.
Any idea why the ability to rename an object in the hierarchy by double clicking might have gotten disabled? Not sure what I changed, if anything. Right clicking and selecting rename works.
it was never double click AFAIK It's click and wait
After it is selected
So yes two clicks are needed:
- Click once to select
- Click again and don't move your mouse for a second
....huh. Yeah that's working. I've been in Unity every day for the last year and for some reason it has felt different the last couple days. Like double clicking quickly used to be more responsive for me.
not sure ๐ค
Hey, is this the right channel to post a question about ball physics?
@somber nacelle โค๏ธ
@somber nacelle Found the physics channel, hopefully I can figure out my friction issue ๐
I want to use the OnCollisionEnter2D function to call a function when two objects with the same script touch but i cannot figure out how to get it to not call the function twice
a common solution for that is just comparing their instance id and calling the method only on the higher or lower one (it doesn't really matter which you choose)
So I have errors that are leaving me confused. Is this the best place to ask for help?\
Given that the common point between the two errors is that you're accesing stuff on Camera.main, looks like Camera.main does not have a value (it is null), which means you don't have a camera object with the "Main Camera" tag in the scene
Trying to access anything on a null-reference like you have now will throw that NullReferenceException you're seeing here in the console.
More info on NREs see https://unity.huh.how/runtime-exceptions/nullreferenceexception
Thank you. I finally fixed it
would anyone know how to use singletons and singleton references? I heard they can be good for certain applications such as referencing certain objects you would use a find method for?
I would love to learn how to use them
here's some info about the pattern and its usages, as well as how to implement it https://refactoring.guru/design-patterns/singleton
and here is some info about how it's typically implemented in unity https://unity.huh.how/references/singletons
sweet, thanks man
at a guess i'd say you copied the code wrong. make sure your !IDE is configured so you see error underlines in your code and get proper auto complete
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข
Visual Studio (Installed via Unity Hub)
โข
Visual Studio (Installed manually)
โข
VS Code
โข
JetBrains Rider
โข :question: Other/None
read the error completely
get your IDE configured. it is a requirement to receive help here
#archived-code-general message
ok
after you do that, it should be more obvious what you've forgotten
totally didnt just scrap the whole thing ๐ญ
but why . . .? it's an incredibly simple issue that requires literally just paying attention to what you are doing
The tutorial was hard to follow anyway. i rather just work with an actual easy to follow tutorial..
okay, well make sure you get vs code configured if you haven't already. using properly configured tools makes this a lot easier
I have for future scripts, but thank you for recommending it.
I'm trying to make a method to spawn units in a square/rectangular pattern. Currently it spawns the units in a diagonal pattern. https://pastebin.com/xQMu6j0y
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.
a filled or hollow rectangle?
Filled
what's num supposed to be there?
the number of points that will be in the rectangle
the size parameter is not yet implemented
sqrt isn't going to implement that correctly
3 would yield 1 and 2
since there's no clean square for that
right
in fact primes would need to be 1*num
so i don't think num really makes sense as the input there
(with nonprimes it wouldn't work either but primes are a clear example)
I see, so what would you recommend?
since it's supposed to be a rectangle, use height and width as the inputs
(sqrt(8) is between 2 and 3. you'd get 6 instead.)
with that the rest of the logic would be trivial
Do you guys know why I'm randomly getting fading for random methods in VS 2022? I've tried flipping the fading settings off and on again, but to no avail
What do you mean by fading?
Like the letters are faded to a light grey rather than a white
Yeah
Ah, ok darn. It's obnoxious.. Thanks!
How do I check if my code runs in webgl?
I can't seem to do #if UNITY_WEBGL
I want webgl specific code to run in this case
some examples I Found require some things that I cant figure out, I was able to do it previous with import __Internal or something, but all examples I see seem to require extra code that I never had to write before.
Is webgl special case that only needs to import __Internal?
#if UNITY_WEBGL && !UNITY_EDITOR
#endif
This line doesn't seem to work, maybe I forgot to enable webgl in the project or something ๐
nvm, VS just doesnt auto complete this line hmm
No clue what __Internal you're talking about. The platform defines that you shared should be enough.
What do you mean?
I just needed this:
// Only run this in WebGL mode.
#if UNITY_WEBGL && !UNITY_EDITOR
PromoImageLinkObjectGlobal.SetActive(true);
PromoImageLinkObjectMenuOnly.SetActive(true);
#endif
It wasn't clear in VS since it didn't auto complete UNITY_WEBGL for some reason, but it might work, just need to test.
As for __Internal it is needed for other reasons(not this one probably) but to run some scripts in a browser for example.
It auto completes tons of other UNITY_ lines but not webgl for some reason, so that got me confused ๐
Yes, that should work. If you're uncertain, you should confirm with the docs.
And yes, Internal was probably needed for something else
I am surprised but the docs actually have something on it
thats actually good to know, last time I had trouble finding any information on that
This is related to conditional compilation and compiler defines. There are plenty of info in the docs on that:
https://docs.unity3d.com/6000.0/Documentation/Manual/scripting-symbol-reference.html
Ah so those werent showing up because my build platform was windows
Is there a better way to ignore certain scripts in webgl mode? In my case I need to disable Steamworks scripts, do I just do #if !UNITY_WEBGL around the whole script?
Also its surprisingly quiet here today, what happened? ๐ฎ
pretty much, or assembly definitions is another way but can be potentially be more work
So I have to do that for all scripts from steam api? ๐ thats a pain, but I will try, maybe there isnt as much as I think ๐
I guess that I should do that for the content of a class, but not the class itself so it doesnt break when steam engine is attached to a game object?
only if you have references to that class it would break in webgl
so having it on game object is ok even if its disabled with #if?
Because it breaks on compilation, hence why I am not sure, but I will keep trying
I wish there was an easy way to remove whole namespace
if its on a gamobject thats an instance so yeah its expecting the script
alright
assembly definition is worth a look, you can choose dlls/libraries based only on platform
I will check it out, but not sure if I can manage to implement it today.
more important stuff related https://docs.unity3d.com/Manual/class-AssemblyDefinitionImporter.html#define-constraints
Thanks
https://i.gyazo.com/a1a602d563139e8c6573c83a10f791f8.png
Is this something I should be worried about?
The game has probably quite a bit of assets, but this seems to take too long?
This is not a big 3D game or anything of that sorts + its webGL build.
1gb of files in Assets/Resources
1.14gb Assets folder as a whole
I am expecting issues, so I am asking if I should wait an hour or cancel it ๐
WebGL would take more time than a normal windows build simply because it has to be il2cpp and then compiled to web assembly or whatever it needs to be.
I see, in that case I will wait till it reaches 1h or so
That being said, I can't say if it's normal or not as it depends heavily on your project and hardware. See if it's stuck on the same thing for more than several minutes. That might point out that it's actually stuck.
No errors in the console, in the past I'd get some errors which were ignored by the compiler until I cancelled it, so this one is promising I think.
compression also takes longer(smaller filesize but long iirc) it really squeezing all that into a webassembly is pretty impressive
what's the error?
is telling you. You have 11274 errors
yes, but what are the errors? the cause of it?
scroll to the top of the errors, start from there
Does your editor give you more specifics? The language server will usually highlight errors for you
nope is literally just that
which platform are you building to
plus it very inconsistent, sometimes it builds properly and sometimes it fails
pc, 2022.3.16f1
You need to update Unity
Also idk how big your project is but with 11000 errors I feel like you could open up any file and see a dozen off the bat
maybe delete the library folder and try again
That is a super old version
where is the engine log files located?
2022.3.52 is available
I used that version as my 2022 for a while so idk if the version is broken
!logs
- deleting library folder rebuild, n try again
- try building blank project
- try another version of 2022
I suspect blank project is fine, it might be something in your project throwing off, I use the same exact version without issues
Also don't build into a folder that has contents
okay
well even though its building to the same build folder, it will overwrite the files anyway
Unity's file io is exceptionally fragile so take nothing for granted
true
Hey, if an object is persistent, (I.e dont detroy on load) when you load into a new scene does the awake function run?
No.
Is there difference between general game loop vs iterative game loop. Exm:
While(true) vs for()
What the difference could be?
Both are loops, but for different purposes
None of these are game loops. They're just loops
Yes, what is the difference of purposes. In which situations one is better than other.
if you need to loop several times with possible jumps I would use for
if you need to do something till something becomes true you need while
that's pretty straightforward tho?
For example i have used while loop in my first game to keep game running. And do stuff inside it. Now in unity i used for. minutes ago this question came into my mind.
well in unity you should just use update or fixedupdate or lateupdate or coroutines ect
You don't need to implement a game loop in unity. It already has one.
Unless you're planning to freeze your game with an infinite loop.
every frame Update() called, every physic frame FixedUpdate() called, you usually put your code in there
you can make your while(true) loop using a coroutine tho, but that's pretty niche
Isnt unity's loop just a main loop which for keep program running? You draw menu, game seperately. I got it like that
I don't quite get what you mean but look at this
https://docs.unity3d.com/Manual/execution-order.html
there are at least 2 (kidna) independent loops of Update which is every frame and FixedUpdate which is every physics frame
each block on that page is the place of the code your scripts can be executed within
You don't need to "draw" stuff manually. The engine does it for you. That's what it is for.
Why are the spline animators so damn slow? Theres 20 spline animations running at one point in my scene and they EACH take 1ms+ to complete, resulting in ~30ms cpu frame times... wtf?
Hello! I'm **looking for a talk **that I watched some years ago, about doing math in the unit range (0..1), does it rings a bell for anyone?
I know it's a long shot but for the life of me I can't find it again, my google-fu isn't the best. Thanks a lot!
hello everyone so im wondering i am not new to coding in fact im really good but i do not know how unity works i whatched game makers tool kit and he said to learn the absoulte basics so what are the absoulte basics?
Maybe the first basics you can start looking at is how gameobject, transforms and monobehaviours work
Create a gameobject, 3d objects always has a transform component (UI uses rect transform instead)
There you can change it's location, orientation and scale
And add components
Although honestly, you should look at some beginner unity tutotials
That should cover most of what you need to know of 'absolute basics'
Thanks, but it's not there. I did ind this one that scartch the subject https://www.youtube.com/watch?v=mr5xkf6zSzk
In this 2015 GDC tutorial, SMU Guildhall's Squirrel Eiserloh takes a dive into the world of 1D nonlinear transformations to help game programmers make better games.
Register for GDC: http://ubm.io/2gk5KTU
Join the GDC mailing list: http://www.gdconf.com/subscribe
Follow GDC on Twitter: https://twitter.com/Official_GDC
GDC talks cover a ran...
If you remember watching it on YouTube specifically, you could try checking your watch history, I believe that is kept for several years back, though I doubt the video may have specifically been titled with "unit range", if it may have been a GDC talk video - the link Simferoce provided is a good way you can use your data with a percentage (between 0 and 1, where 0.5 represents 50%), so if you had a range of numbers between 100 and 1000, and you wanted 750, youd get a lerp(100, 1000, 0.75f) or if you wanted to smoothly transition between 2 points you can lerp with a Vector or Quaternion (for rotations) - you can also mathematically calculate numbers to fit a percentage if you know your range, for example if you wanted 50% of 500, thats 500 * 0.5, or if you wanted to know what percentage 250 is from your max value, thats (250 / 500) * 100 - not 100% sure if that is what you mean with "unit range" or if your referring to a different kind of math, you could try looking up the math terms for that specific kind of math otherwise
learn some unity and C# #๐ปโunity-talk message
Sorry, I should have said that I'm not looking for advice on how to do it, but talks about it to share these ideas
Ah then if its about sharing, going through your YouTube history or looking up the math terms for that specific kind of math might be your best bets, or possibly searching through GDC Vault channels, but that could be a long shot of mostly guessing the title/thumbnail and hoping its there
How are C# arrays initialised? If I declare an array of 64 CustomStruct type, will called new() on the declaration assignment initialise empty structs in the array? Or will it be some form of uninitialized garbage value?
they're default-initialized (zeroed)
Okay thanks
Would it be possible to override the default constructor used for default initialization in the version of .NET Unity uses? Since value assignment to members aren't available in this .NET version
i already know c# pretty well may need a refresher though
okay thank so much
that's just how structs work, even if you use a version of C# that lets you give a struct a default constructor it's not called in all circumstances (like allocating an array) since it's really just a block of memory
No problem, good luck Kali
if you want a type that can only be constructed by its contructor, you need a class
I see, thank you
in the pinned message I posted there is unity tutorials which will be of use to you, you would also want to learn unity's API if you have not already
okiedokie thanks
so you mean c# discord?
huh? I do not think that is what I posted, this is what I meant #๐ปโunity-talk message although you can join it if you have questions for them
yup i did
oh i saw it ima go read it cya
Hey guys, anyone got experience with Unity Version Control? Working on a Uni project with my mates, but they can't check in their changes. They keep getting the error "You don't have add, ci permission on [file name]", even though they're all marked as owner in the organization which is inherited on the project.
Nvm, it doesn't automatically assign seats to people joining the project, even if they're an owner from the organisation.
How do I assign refs to members of a struct? I wish to pass refs as part of the members of a struct so that a child may store direct refs to data of its 'grandparent'
Or is this not possible
do you mean to assign components that belong to a GameObject?
No, similar to how you can assign a pointer or reference to another object to allow it access to the data defined by the assignment
std::shared_ptr<CustomStruct> m_attackData = std::make_shared<CustomStruct>();
childObject.m_attackData = m_attackData;
that's just assigning the component to the variable . . .
myStruct.refVariable = someComponent;```
it seems that my struct is storing a copy tho
are you storing the component or a value from the component?
Yeah, that would be what it does with the solution suggested.
I am storing custom struct values
public struct MobAttackData
{
public bool hasInit;
public float damage;
public PropertySet interval;
public MobAttackData(ref float damage, ref PropertySet interval) : this()
{
hasInit = true;
this.damage = damage;
this.interval = interval;
}
}
That is not really how should do that in C#.
Could you suggest how I may do it or point me to some resources regarding this please?
ref float damage is not something you would expect to work with in a C# environment.
Use a wrapper.
public MobAttackData(StatisticReference damage, ...)
If you really insist you could also use System.Func. But manipulating value type data with ref is uncommon.
though using ref points to the original value, this would not work since damage is a value type. when the struct is created it becomes a copy. you need to have a reference to the component the value belongs to (that's what i thought you wanted) . . .
I'm sorry I don't really understand this, is there a web resource that can elaborate on this particular implementation? So sorry for imposing on you
The parent doesnt store everything in a neat way, encapsulation would have me making an ungodly amount of Getters though
you can do not use Constructor at all and you can just initialize via new var mad = new MobAttackData{hasInit=hi,damage=d,interval =inter}
maybe seeing the entire code/hierarchy can give us a better picture. also, what is your intent or the purpose of your structure. there could be a better solution . . .
public class Statistic
{
public float Value {get;set;}
}
public class MyClass
{
private Statistic statistic;
public void MyFunc()
{
new MobAttackData(statistic)
}
}
Alternatively
public struct MobAttackData
{
public MobAttackData(System.Func<float> damage)
}
public class MyClass
{
private float damage;
public void MyFunc()
{
new MobAttackData(() => damage)
}
}
if u use MyClass name -> method with same name is Constructor in your case -> public MobAttackData (ref float damage, ref PropertySet interval) is constructor that have no sense
Or a more C# object oriented way
public struct MobAttackData
{
public MobAttackData(IDamageProvider damageProvider)
}
public interface IDamageProvider
{
public float Get();
}
public class MyClass
{
public void MyFunc()
{
new MobAttackData(new DamageProvider())
}
}
Struct
public struct MobAttackData
{
public bool hasInit;
public float damage;
public PropertySet interval;
public MobAttackData(ref float damage, ref PropertySet interval) : this()
{
hasInit = true;
this.damage = damage;
this.interval = interval;
}
}
LaserDrone : Mob : Monobehaviour
protected override void Start()
{
base.Start();
m_health = new(0, m_maxHealth, m_maxHealth);
m_attack01 = new(0, m_maxAttack01Interval, 0);
AttachEventHandlers();
m_weaponSpriteRenderer = transform.Find("Weapon").GetComponent<SpriteRenderer>();
m_weaponColor = m_weaponSpriteRenderer.color;
m_bodySpriteRenderer = transform.Find("Body").GetComponent<SpriteRenderer>();
m_bodyColor = m_bodySpriteRenderer.color;
m_contextMob.TransitionTo(new LaserDroneType_Mob());
m_contextMob.RegisterAttackData(new(ref m_maxAttack01Damage, ref m_attack01), 0);
}
MobContext : Monobehaviour - Another component running alongside Mob(Type)
public void RegisterAttackData(MobAttackData attackData, int idx)
{
m_type.RegisterAttackData(attackData, idx);
}
IType_Mob
public void RegisterAttackData(MobAttackData attackData, int idx)
{
m_attackData[idx] = attackData;
}
I see, this would be something related to what I was envisioning as an alternative solution
Thank you anyways
sorry, afk. if i'm correct, it seems like you want to use a struct for tracking changes of your data. a class is preferred. since structs are copies, they're best for immutable data, or data that is changed independently from its copied source . . .
you can create a Stat class if you want to track changes of that value and pass the class instead, or add a method on the struct to update that value for a simple fix, though, you'd have to track when that value changes and update the struct accordingly . . .
Nw! It's alright I've refactored my code already, I was under the assumption structs in C# were similar to C/C++
Along with references
The reason you can't do this in C# is because it's a safe language. There are scenarios where you can use ref the same way you'd use pointers in C/C++, but they are very strict to ensure memory safety.
But if you use unsafe, you can do whatever you want.
ah, gotcha. yeah, they're value types instead of reference types . . .
there are no value/reference types in C++, everything is a "value type" in C# terms
also, quick nitpick. if the SpriteRenderer for "Weapon" and "Body" are part of the GameObject hierarchy, it'd be easier to drag and attach those components from the inspector than use Find and GetComponent for each of them . . .
Here's the C# unsafe equivalent of the C/C++ example you gave, but normal pointers because there are no built-in shared_ptr type in C#.
public unsafe struct MobAttackData
{
public bool hasInit;
public float* damage;
public PropertySet* interval;
public MobAttackData(float* damage, PropertySet* interval) : this()
{
hasInit = true;
this.damage = damage;
this.interval = interval;
}
}
Gotcha ๐ซก
was just about to ask why not shared_ptr . . .
the C# equivalent of a shared_ptr containing a struct is just a C# class, idk why you wouldn't just use that ๐
This looks simple enough, if you can stomach the unsafe, but it's not very useful in C# because you can't easily create a pointer to something that was allocated by the garbage collector, which is everything unless you or Unity allocated it manually.
Thanks, didnt know I could actually declare raw pointers.
it's just an example of how they can achieve what they were trying to do from the their knowledge of C/C++ . . .
i think it's worth pointing out that can and should are very far apart here though lol
wait, you're entire game isn't written in unsafe C++? blasphemy!
to be honest it's probably better to compare the unsafe features in C# to plain old C than C++ because C# is missing all features like RAII which you can use to make C++ a bit safer
Hi, I'd like to use a graphical interface to plot a velocity curve and turn it into an array of values. Are there any utilities that exist for this? E.g. in this video, they present visual curves representing the vertical velocity of the character, and these values are hardcoded on a per-frame basis, which is what I want to try in my game
So in the video, for Yoshi, his double-jump velocity is probably something like [-1, -.5, 0, .5, 1, 2, 4, ...], and I want to be able to plot these values and convert them into an array
you can use an AnimationCurve
you could either use the intended curve functionality of using a few plotted points (2-4 points) with interpolated handles, or you could technically plot every frame manually by placing points at a certain interval
you could then just use the Evaluate method on the AnimationCurve in a for loop to assign the results to an array
oh, excellent, thank you, I'll play around with this
so i'm trying to create a melee attack hitbox for my player character, but i'm struggling a bit on the enemy detection, should i be turning on an object with a box collider trigger with a script to detect OnCollisionEnter, or create an array with OverlapBox?
i'm trying the former, since its easier to change its position/size, but i want to know if there's a better option
Just do a direct physics query
turning on a collider and waiting for a callback has all kinds of weird timing and coordination issues
Anyone know why there is no option to merge branches in Unity Version Control?
Are you looking at branches? Or the changelist?
Branches
I've looked everywhere for an option to merge but it doesn't seem possible
Not sure - try updating everything to the latest. If still not working, there are otehr ways to do it, including from the command line, or on the unity cloud dashboard
I'm not super familiar with UVC, I normally use git.
I was told Git use in Unity was a paid feature. Or did they get rid of that?
Git is and always has been free and open source software
What you are using (Unity Version Control) is a paid feature (after certain limits)
Maybe I've already hit the limit? I am a solo dev so this seems incredibly limited.
doubtful
I'm not convinced the plugin in the uNity editor ever had the ability to merge branches
But then again, I haven't used it much
There is supposed to be an option when I right click so I don't understand.
not the Unity Editor plugin
It's just a 3rd party plug in? That's seems like a major oversight.
so physics.overlap then?
Sure
Is there a way to tween Transform.LookAt(), or achieve a similar result through other means? (Slerp probably) LeanTween makes me feed in the necessary rotation, which I don't know how to calculate
Sure of course. LookAt merely modifies the object's rotation
To calculate the LookAt rotation you'd do this:
Vector3 direction = targetPos - myPos;
Quaternion targetRotation = Quaternion.LookRotation(direction);```
You could also tween an object between where you're currently looking and where you want to look and LookAt that object.
Same effect.
Git is not a paid feature, though there are a few steps involved to get it setup with a proper .gitignore file for Unity, and there can be limitations with pushing large asset files, using git LFS becomes paid for increased storage, but aside from that, its essentially free and you either access it through a website, console/terminal or with a gui program like "github for desktop" or "source tree", etc
using git LFS becomes paid for increased storage
For the record git LFS and Git itself are completely free and open source software.
If you choose to use a cloud hosting Git Repository provider such as GitHub, you will need to pay for certain things.
But if you want to self-host a git repository you can do so without any limits
I'd really prefer to just use Unity built in mechanics but it seems they don't work at all.
I just used Unity Dev Ops Version control and I nearly lost everything.
Ah good point you bring up, I was referring to github specifically as thats whats often used, where limitations exist, but you are right that if your self hosting your limitations is on your own hardware then (though I personally havnt tried that myself)
Like it said it merged branches but I didn't see any of my changes once I switched back to my main branch.
Yeah I'd really recommend using real battle-tested version control aka Git
There's way more support and knowledge for it in the world
It just seems weird that it doesn't work. Don't pro studios use this?
I'm just weary of using anything that isn't meant to work with Unity
Although some may be swithcing to it to fulfill certain contractual obligations for enterprise customers these days
Git is meant to work with everything
There's nothing special about a Unity project in terms of version control
Git is the standard in quite literally every other field of CS. You dont need integrated version control, especially since these arent as good
At least when I looked into it a year ago, some other version controls didnt even have the same basic features as git.
Like merging branches?
I dont remember exactly what it was, but some dont even let you edit a file the same time as someone else.
Unity has also rebranded their version control I think 3 times now (used to be "Collab" then Plastic, then UVC), as there seemed to always been a feature youd find in a regular git missing or not functioning as expected, im sure its a great tool because its integrated with managing asset files like scenes and prefabs well, but you can also do that with a few more clicks outside of Unity (though I havnt used UVC in a while)
So yeah this is the very reason I am afraid of using any other source control
I don't want my prefabs and assets getting messed up.
why would they get messed up?
they're just files
Youd have to mess up pretty badly to do this. Which doesnt matter anyways because you'd be using version control and can revert
slap a .gitattributes with * text=auto eol=lf if you feel like it
From my experience, using github externally, I never really had issues with files getting messed up, but like any tool, it does take time to learn, however, it is advised not to work on the same scene as someone else, files wont get messed up, but you may have to "diff" those files
git is meant to work with everything else, it's a much more general tool; ides have git integration, and if you learn git you'll be able to use that for any other project since it's nonspecific
Github is a paid service unless I want to expose all of my work to the rest of the world right?
no
no
Thats actually handy, I didnt know about thee eol attribute could be done with git
you can make private repos for free on github
it's free to have private repos
(has anyone mentioned the *hub comparison to explain git vs github yet)
Yeah I get the difference. I've used github for a few mobile projects. I was under the assumtion that you couln't have private repos without paying monthly for them.
How long has that been a thing.. I've been paying lately since my free student deal ran out
several years now
you've been paying for the private repos on github?
I think because GitLab or BitBucket started offering free private repos GH had to start doing it
the change was in like 2019
When I started, private repos weren't free
Oh wow, til
Same
If it helps: https://github.com/pricing - first column "free, 0 USD/month", explains public/private repos (and other limitations)
I havent looked at the actual pricing/plans ever since I got my student deal ๐
I just use github for free and it has been working for me ever since
Tbh, neither did I until I compared github to gitlab a while back lol
I would like to look at more git based Version control but I don't know of many other than github
Ive only ever used github, gitlab, bitbucket and " TortoiseSVN", the latter was my least favorite
TortoiseSVN is a version control software? I did not know that or I'm confusing it with something else
kind of, SVN is the version control bit, tortoise is a gui for it
oh wow, i never knew you had to pay for that. luckily, it was free when i started using it . . .
interesting, never used an SVN based version control system before, I always used git based products as it usually works well
Yeah, ive only used TortoiseSVN on one project and it was... Much more awkward than using github/lab for sure, but im sure it came down to unfamiliarity... At least thats what the boss on that project said
I used SVN/Tortoise in my first job out of college, it was alright.
Git is better ๐
yes git is 110% better, its very easy to use as well and the GUI's (most of the time) are great, I have not used git's SLI either at all or not to much, I do not remember
Hello, what is the most optimized method for placing an object picked up in the hand?
Simply have all the 3d items placed in advance and activate the one you've picked up and deactivate the others?
"Simply have all the 3d items placed in advance and activate the one you've picked up and deactivate the others?"
It's a fine idea assuming you've a limited amount of weapons a character can have.
yeah. Otherwise I guess you'd have to store the mesh item on the object and retrieve it dynamically?
I'm working on a multiplayer project, and I want to avoid sending too much data to the server.
If we're talking about Doom, and similar type of games where you've got like 10 weapons max then I'd go with the activate/deactive route. If it's Borderlands where there's hundreds of different weapons that can be generated, then you're looking into new()ing/Instantiating the weapon onto the player when they retrieve it most likely
Rather, if you're doing some drop system that has weapon variance then you'd instantiating on the drop, then read in its configuration and childing it to the player on pickup*
so read the object's data and update the player's hand with the data.
I don't know how many items I'll have in play.
If you've no variance on your weapons, such that a broadsword does 7 damage like any other broadsword, then you simply need to serialize the IDs of that item. If the weapon can randomize range of damage from 5-7, then you're usually passing in a struct of data instead of just an ID.
Least of your problems though relating to networking serialization
Hey, i would i appreciate if I got some insight on this problem
Quaternion rotationY = Quaternion.AngleAxis(currentRotation.y * parallaxRotationScale.y, Vector3.up);
Quaternion combinedRotation = rotationX * rotationY;
Quaternion finalRotation = Quaternion.Slerp(
combinedRotation * Quaternion.Euler(rotationOffset),
rotObj.transform.localRotation,
slerpScale
);
rotObj.transform.localRotation = finalRotation;```
i've been struggling with this for a couple of days; im trying to have an omni-directional rotate for the obj rotObj based on player perspective, aka the Camera
the rotationX works just fine, leaning up or down no matter what orientation, due to it being based off the camera POV,
but rotationY is being stubborn, and refuses to pivot on the Y axis
What's the idea around doing all that work with quaternions only to tack on some offset in eulers near the end
also when you're combining rotations in xyz fashion usually it's ~~z -> y -> x ~~ z -> x -> y like Andy mentioned below (but assuming you don't use unity's eulers methods you can order however you want as long as you stay consistent)
Might be the issue, I think that was left behind from old solutions
For Quaternions?
Interesting, Iโd have to research more on Quaternions and Eulers
eulers , as far as unity methods go I think default by multiplying ~~z -> y -> x ~~ z -> x -> y
hello, so i have weird problem, and thank you if anyone helped,
i don't know why, but my private variable suddenly changed on runtime, even nothing change it both in the inspector or in its own script,
the weird private variable is inside ScriptableObject, and the ScriptableObject is inside an enemy
name of the variable is enemyGroup with type List<Character>,
i thought something wrong with my unity, so i tried to restart my laptop
here's the full script of it : https://paste.ofcode.org/ND377n7fS3HGXcMurcVyRJ
and i also provide a video
maybe this? you're assigning the same list to both enemySpawn and enemyGroup then clearing it
well, clearing it next time that method gets called i guess
you also have methods returning enemyGroup by reference so it could be cleared from elsewhere in the code
Can you show an image of the full error/stacktrace in the console window?
The error doesn't have any relation with this script, its another error
Wait let me turn my laptop on
I only change the enemySpawn List, never change enemyGroup List
do you not understand that when you do list = list they become the same list
yeah i know,
if ListA have a,b,c
and ListB have nothing
if ListB = ListA
then ListB wil have a,b,c
is that what you mean?
no not at all
ListB is just an alias of ListA, it is not a List in it's own right
ListB is independent, so if i change anything in ListA, ListB will still the same unless i change ListB
no
not in this example
I think what you want to do is ListB.AddRange(ListA)
otherwise ListB ceases to exist. You would be left with just ListA in memory (ListB variable would just point to ListA internally)
wait, let me think
what's this code does?
adds all the elements in ListA to ListB
so basically, what happend in my code is ListA value is connected to ListB, so if i change one of them, others will also changed?
yes
ahh ok, i just realize that, thank you btw
be careful though. AddRange is a shallow copy.
in your case the Character references pointed at by the Lists will still be the same ones, not copies
okay
If variable a is a reference type and you assign b to a, you assign the same thing
I suggest you learn the difference between reference types and value types because it's actually really useful to understand what these are
If you want to create an independent list, create a new list and use the constructor that accepts an existing list. This effectively clones the list
Note that if the list holds reference types by itself, these will also be the same as the entries in the other list
I see SteveSmith also pointed this out already
i have to translate all of that then read it carefully phrase by phrase, but thank you
Just look up reference types and value types in C# and also the difference
That's the important part
i wanna do a function to restart a video player and when it is called:
1- Video stops
2- Video is reseted to the first frame
3- texture showed is the first frame of the video.
i dont have issues with 1 and 2, but how can i do 3?
Hey guys, don't know where's a good place to ask this so I'll ask here. Does anyone know of an Ad SDK that permits you to reward rewarded ads with crypto? AFAIK Google's policy disallows this, specifically any reward with financial value.
how would you guys call the button in the credits to go back to the main menu ? Like "Back" ? "Menu" (like here) ? "Title" ?
Call it whatever you want, or use a an icon, this isn't a coding question.
Sorry, no idea, but a Google search gave me this https://discussions.unity.com/t/how-to-extract-frames-from-a-video/782327
I don't really get when one should use Awake() vs Start()
check the unity !docs and the #๐ปโcode-beginner channel . . .
usually Awake.
Start when you want something to happen after other initialization is done (including initialization that other scripts do, like when instantiating this object as a prefab and setting up some values first)
I have a problem with my 3D player character that can slide and crouch. For some reason, if the player slides into a wall and then jumps, the jump detection system stops working. Specifically, this part of the code stops functioning:
Physics.Raycast(origin, direction, out hit, ray_Distance);
I have no idea how to fix this.
what does "stops funcitoning" mean exactly?
What debugging steps have you taken?
Is the code still running?
Physics.Raycast(origin, direction, out hit, ray_Distens);
if (hit.collider.CompareTag("Ground"))
can_Jump = true; // if it found ground
else
can_Jump = false; // if there is no ground```
I will say onet hing - that this code isn't even making sure there was actually a raycast hit
You are ignoring the return value on Raycast
Yes, everything else works. Debugging involved slowly and painstakingly figuring out whether the issue was with the Raycast or something else. It turned out to be related to this part: Physics.Raycast(origin, direction, out hit, ray_Distance);. After the event, it doesnโt update.
When I say it "stops functioning," I mean it stops updating the can_Jump variable.
if the raycast doesn't hit anyhting, this code is going to cause an error
It's definitely updating the variable
assuming it's still runing, and there is no exception
are you looking at the console window?
This is why i asked what debugging steps you've taken
you need to check
- If any exceptions are being thrown
- If this code is actually running
- What the result of the raycast is if it is running
aaa
Debugging involved slowly and painstakingly figuring out whether the issue was with the Raycast or something else
But what debugging steps did you take?
With Debug.Log figuring this out would take about 2 minutes, it would not be painstaking
ill come back with debug lists and come back
kinda did but also removed becues "i felt like a smart fellow" XD
private void JumpingPlayer()
{
Vector3 origin = transform.position + ray_Offset_Down;
Vector3 direction = Vector3.down;
Debug.DrawRay(origin, direction * ray_Distens, Color.red);
//hit = Physics.Raycast(origin, direction, ray_Distens);
Debug.Log($"DEBUG JUMPING : hit colider object = {hit.collider}");
Physics.Raycast(origin, direction, out hit, ray_Distens);
Debug.Log($"DEBUG JUMPING : Physics.Raycast reslut = {Physics.Raycast(origin, direction, out hit, ray_Distens)}");
if (hit.collider.CompareTag("Ground"))
can_Jump = true; // if it found ground
else
can_Jump = false; // if there is no ground
Debug.Log($"DEBUG JUMPING : can jump is = {can_Jump}");
}
Ok so... why are you just ignoring that exception?
Like I said you need to actually check if the raycast hits something
how do i do that
if (Physics.Raycast(origin, direction, out hit, ray_Distens)) {
// we hit something
}
else {
// we didn't hit anything
}```
thanks
ill be back
private void JumpingPlayer()
{
Vector3 origin = transform.position + ray_Offset_Down;
Vector3 direction = Vector3.down;
Debug.DrawRay(origin, direction * ray_Distens, Color.red);
//hit = Physics.Raycast(origin, direction, ray_Distens);
Debug.Log($"DEBUG JUMPING : hit colider object = {hit.collider}");
Physics.Raycast(origin, direction, out hit, ray_Distens);
Debug.Log($"DEBUG JUMPING : Physics.Raycast reslut = {Physics.Raycast(origin, direction, out hit, ray_Distens)}");
if (hit.collider.CompareTag("Ground"))
can_Jump = true; // if it found ground
else
can_Jump = false; // if there is no ground
Debug.Log($"DEBUG JUMPING : can jump is = {can_Jump}");
if (Physics.Raycast(origin, direction, out hit, ray_Distens))
{
Debug.Log("raycast hits somthing");
}
else
{
Debug.Log("raycast did not hit anything and makes me sad");
}
Debug.Log($"raycast hits : {hit.collider.name}");
}```
sorry i am so lost
notice how you've just put that if statement after your actual raycast and the code that is throwing the exception when the raycast hits nothing
hit.collider is outside raycast if statement that defeats the point of having that if statement, you can only log hit.collider.name, if the hit actually happened
Don't be afraid to snag the code line numbers in screenshots lol
๐ 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.
do you understand what the actual purpose of the if statement is?
in what part
wdym "in what part"?
why do you think Raycast returns a bool
Do you understand the meaning of any of the code?
so then one can get the result of it hitting an object form there it saves values (or well i thing )
yes
so if it tells you if it hit something. using the result, why are you using the result outside that statement
Then it should be pretty straightforward and you would realize it doesn't make sense to have multiple Raycasts here
you mean this part
yes, how could you log the name of a collider that might be null? hence your error
i ripped the raycast form a nother thing i was working on in the pas with 2d
if it is empty then there is no hit
you cannot access the propery of a null object, name is a property of collider
if your raycast hits nothing, that line returns error
Not really. You are learning.
yes this belongs in #๐ปโcode-beginner though
well i know enuff i just thot of somthing else and my mide was not set that i had fliped up the raycast system (meaning the understandment)
becues i got a hang of it in the 2D verson and now realising 3D in a bit more compleax
in this channel you should be expected to know the purpose of the code you post or how nullref works
anyway, the fix is simple and you should remove the raycast without if check
the compare tag can still throw null, do you not see why
read the logs again carefully, you wrote them lol
XD
is there a way to prevent "assuming" the case for the asyncLoad variable initialization?
e.g. I'd rather have this format
just pass in the actual name of the scene you want to load as nextSceneName and pass that to LoadSceneAsync
ye now i am seeing more of the problem
oh
holy fuck man
i'm tired
thanks lol
btw the can_jump = false should probably be in the else of raycast also
if else is redudant though you can just make a variable for the raycast
bool hitSomething = Physics.Raycast(etc..
isGrounded = hitSomething && hit.collider.CompareTag(etc.))
aaaaa
meaning is just a bit eayser to rework it a bit more. thanks guys for all the help. and next time ill be in the beginner XD
Do you guys know how to prevent the preselection of the first button ? (canvas)
Setting Navigation to None does not seem to change anything
what about eventSystem.SetSelectedGameObject(null); ?
public void ClickReset()
{
menuEventSystem.SetSelectedGameObject(null);
}``` my menu script calls this function everytime I click a button or slider so it doesn't remain selected afterwards..
probably could call it in Awake() or Start() for ur usecase
Hello fellas, can somebody help me with Unity's Behavior Graph? Just tried to test it, but seems like serialization of private non-BlackboardVariable doesn't work or maybe I just do it wrong somehow?
Following docs: https://docs.unity3d.com/Packages/com.unity.behavior@1.0/manual/serialization.html
Right now I use 1.0.5 version and this is content of custom action node:
[Serializable, GeneratePropertyBag]
[NodeDescription(
story: "Search <b>Ability</b> in [unit] and saves to [saveTo]",
category: "VOIDRPG/Blackboard",
id: "30d4a9d03c14e6ada6372d4db5d07924"
)]
public class GetAbilityAction : Action
{
[SerializeReference] public BlackboardVariable<UnitObject> unit;
[CreateProperty] public Node Child => m_Child;
[SerializeReference, DontCreateProperty] private Node m_Child;
[SerializeReference] public BlackboardVariable<BasicAbility> saveTo;
protected override Status OnStart()
{
Return Status.Success;
}
}
And this is result in Behavior Graph:
!vscode
ok so uhh idk if this is good for this channel but
uh how do i fix the package named "com.unity.settings-manager" failing
Library\PackageCache\com.unity.learn.iet-framework\Editor\Core\FrameworkSettings.cs(3,19): error CS0234: The type or namespace name 'SettingsManagement' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?)
i cant find ANY solution
i just wanna do some MR things :(
Version compatibility issue probably
wha-
these are the packages that come when u make a project
trying to use
the MR package
Is that a project from unity learn?
No clue what MR is
But make sure that you're using the same editor version
Do they?
Do they use the latest editor version?
WDYM
Share the page where you got this project from
You said it's a unity learn project, so it must be from a tutorial?
do you have the settings manager package?
it's a package it looks like you need in the package manager as it is missing a reference to it
I have never used it though
so you do have it? That is the package name yes
no
if you do have it you can try what dlich said
Sounds like that's the underlying cause of the issue. Either a connection problem or access rights
usb?
USB?๐คจ
you have unity installed to a USB??
...yea why
i dont have 12 gb on my computer
and i dont wanna delete steamapps/common (90gb :D)
Well, it's probably not gonna work correctly with an external storage.
No wonder it cannot access anything, you are not supposed to have it on an USB
what .EXE?
the unity 6 installer
"not work correctly" doesn't mean you wouldn't be able to launch it at all. It means that there would possibly be problems, like the one you're facing.
well it could load into the editor but with that error
Well, try to install it on an actual internal storage.
i cant
so you offline installed it onto a USB, which you are not supposed to do. You should instead install it via unity hub online and on the actual C: drive
Then there's not much we can help you with.
Do you only have 4GB on your PC? Is it 20 years old or something?
you cannot, also you shouldn't push your hard drive to the limit like that as it could cause damage over time
Well, delete something
how did you fill up 512 gb hard drive that much ๐
one video game series + mods
its like 90
and the rest is idk
90 GB*
man even with deleting downloads TWICE i still had like 400gb left after a while on my old 2tb pc lol
and i had like a bajillion UNITY versions on that
but this is off topic
@storm lagoon This is not tech support channel. Install Unity properly to any location through the Hub.
You have something taking up 300GB+ and you don't know what it is?๐
its just alotta >1gb files lol
better purge some of those files
@storm lagoon I'd rather you stop posting off-topic.
does anyome know how to allow the player to drop an audio file into the game
Like drag and drop?
yes
Quick search led me to this
very epic thank you
Only on windows and must be built
i think the thing im using to convert audio files is windows only too so its okay
GRAAAAAAAAAAA
this might not be the place to ask but does anyone know what might be causing my monobehaviour functions to be showing up as unused in VS
i have the visual studio extension installed
this only started happening a few days ago
this class inherits from monobehaviour
FOR ANYONE LOOKING AT THIS LATER SOLUTION IS HERE:
https://developercommunity.visualstudio.com/t/Private-Unity-messages-incorrectly-marke/10779025
it shows as unused because you don't manually call it. Unity invokes the event function through reflection . . .
Does anyone know why my player slides across the ground when I stop moving?
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.
VS has never showed me this before now
i know it's not literally manually called but is there a way to get rid of this?
just for the monobehavior functions
it's probably from an update. maybe you can remove the suggestion from your IDE settings . . .
they already have a FixedUpdate method and they do handle movement in FixedUpdate . . .
i am stupid.
also, using deltaTime in FixedUpdate automatically changes it to fixedDeltaTime . . .
it is set to the default 0.05
But I don't want to increase drag because it doesn't get rid of the problem, it just makes me have to increase my player speed, which also increases the amount of slippage so it's basically useless to increase it
Because objects have inertia
this might be helpful, hopefully i'm right this time xd
set your ground/player to a physics material with higher friction
is there a good way to remove it?
If you want to immediately set the velocity to zero, there's nothing stopping you from doing that in your code
I've tried and for some reason that doesn't work
But physical objects don't act that way naturally
@leaden ice thank you for helping me with my many mirror questions a few years ago :)
What did you try exactly?
rb.velocity.Set(0, rb.velocity.y, 0);
Not generally no
You did something wrong
What did you write and what error did you get
rb.velocity = new(0, rb.velocity.y, 0);```
E..g
i'd remove multiplying by deltaTime when using force. basically, by doing so, you've manually changed the ForceMode to Acceleration . . .
i tried it again and didn't get the error so I have no clue what I did wrong earlier
So now the player doesn't slide, but for some reason the camera like bounces let me take a video rq
If you mean it's jittery that's generally due to a lack of functioning interpolation on your Rigidbody
That can happen if you didn't enable interpolation or if you do something to break the interpolation, such as directly modifying the object's Transform
How do I prevent "selecting" buttons?
In my project I use space for certain things, but when clicking a button space would activate that button until I click outside to "deselect" it.
I never experienced it before, but it seems like a big issue to me.
Newest VS is bugged, that's why it does this
Before it would correctly show it as methods called itnernally and not unused
hello, so i want to use event with parameter, but functions that subscribe the event don't have to use the parameter
i know i can do this, but i don't want to
void Start()
{
eventProvider.OnSomethingHappend += Subscriber;
}
void Subscriber(string blank)
{
// blank is never used
}
instead, i want something like this
void Start()
{
eventProvider.OnSomethingHappend += Subscriber; // no error in this line
}
void Subscriber()
{
}
Pass the parameters and don't use them?
Alternatively, pass the parameters and have the event handler method call another method that doesn't use the parameters
These things are basically required so you can't work around them
You can also place a delegate on the event directly but I suggest you don't do that since you can't unsubscribe from these since they're not tied to an actual method. Even then, the delegate must reference the parameters regardless
what's actually happend in my case is, i have one event with parameter, and there's two function that subscribe it, one that require parameter, and other one that don't require parameter, i don't really want to make a mess so i don't use code example above
or maybe i should use two different event
There's no "mess" when you have unused parameters
This is very common with events
Also, event handler methods should purely exist to handle the method, so it would be clear why a parameter is unused
But, if you want it to be even more clear, you can make your parameters _, __, ___ and so on to indicate they are discarded
This is an actual .NET feature, albeit usually for method variables and not parameters so they are not actually supported in this case
It indicates you are aware there is a variable, but you don't use it
Okay then, maybe i should ask my senior first
My experience with senior is that they tend to give some old and horrible C++ solution so I'm not sure if this is the best idea
Anyone know how to make unity games require double swiping when using gesture navigation in android? and how to make it recognize as a game?
I already tried using a custom manifest and adding android:isGame=true and android:appCategory=game
any "unity games"? Or specifically the one you're working on?
the one I'm working on, sorry!
should've clarified
Well, you'll need to implement it. There's no built-in double swipe feature.
I'm pretty sure it's part of android gesture navigation tho
fullscreen apps typically require double swiping from the bottom to go to the home
altho google hasn't been very helpful with figuring this out, so I could be wrong
I don't seem to have such a feature on my phone. If it is an os feature, it should work with any app, including unity games.
do you have the 3 buttons on the bottom of your screen when you use your phone?
back, home, task view?
(also, about to go in a meeting, will return ASAP)
Yes
I believe for iOS it's a tick box in the player settings. I haven't thought about looking for it for Android
Android has an option to change to gesture controls, making it the "same" as iOS - no idea when this got added
(in case you weren't aware)
this is a code channel, and your question isn't code related. Delete and move to #๐ฑโmobile
np. thanks for letting me know ๐
this isn't a code question either, delete and ask in #๐ฑโmobile as well
oh thanks I didnt know where to ask it, let me move it now.
Oh thank you I didn't know we had that
My senior is also a lead programmer ๐, so i have to listen to him or i will get deleted
I have a quaternion, how do i get the angle for a specific axis from it? like the rotation on the Y axis
You can convert it to Euler angles and use the value of the desired axis.
ah okay
Would love to hear what your senior said
Hฤฑ, i followed a car movement tutorial with wheel colliders and rigidbody but my car is so slow. Do anyone know how to make it faster
Ive tried to fix it with chatgpt but none of his ideas fixed
Nobody knows how to make it faster until your share your !code and define what "slow" is in this case. I'd assume in terms of speed, not 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.
Don't rely on ChatGPT to fix your code. Get rid of this habit immediatley because you will just end up with more broken code.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hi! When loading a scene asynchronously, does it also run the Awake() and Start() functions of enabled objects asynchronously? Or will the game crash/freeze if there are too many operations?
It runs synchronously or asynchronously based on the method signature
I.e. if the method returns Awaitable, it will be asynchronous just like anything else
There's not really an async in Unity I believe. It's all synchronous with some tricks
I'm still not fully sure what it does
Unity is single threaded except for very special circumstances
Thank you both. Can I make the LoadSceneAsync wait for an IEnumerator to run?
Hah, I figured as much. That's usually the case . . .
So I can force it to wait for an IEnumerator this way?
If you mean it will wait for Start to finish then no
I believe Start works independetly and your scene loading has nothing to do with it or the order of execution
I believe Unity only ensures Awake runs first, then Start
Ah, okay. What if I put it in Awake()?
Well same thing
Is your issue that you must wait for something to initialize in another scene?
The thing is, I have a world generator that is an IEnumerator, and I want it to finish before switching scenes
Yeah
https://docs.unity3d.com/ScriptReference/AsyncOperation-allowSceneActivation.html
let the generator finish, then manually activate the new scene
I want to make a system where:
- if there's a
yield return, then it will wait for the animation to finish before executing the next animation - if there's a
StartCoroutine(), then it will execute the next animation without waiting
But for some reason, when I run the game, the longer animation (which is _drumsInstrument) wont wait for the shorter animation (which is _fluteInstrument) to finish.
This is what shows for me
Nevermind; fixed the issue.
It was the Has Exit Time property ๐
from what I understand I have to use setSystemGestureExclusionRects in android to make it defer the home gesture in gesture navigation mode, but it's not clear where I should do that. does anyone have any tips?
How do I load an animationclip into a Unity project from files?
I have an .anim called Idle and I want to modify a game's idleAnim. How do I do it? I'm talking about modding here, but I'm curious about the Unity specific 'loading'. Do I use assetbundles, or resources.load?
Hi,
I have a base dictionary with a generic object and an enum for my stats that all scene objects use and its working well.
public class StatsInfoDic : IEnumerable<KeyValuePair<StatsInfoTypeEnum, object>>
{
private Dictionary<StatsInfoTypeEnum, object> _dict = new Dictionary<StatsInfoTypeEnum, object>();
public void Add<T>(StatsInfoTypeEnum key, T value)
{
_dict.Add(key, value);
}
public T GetValue<T>(StatsInfoTypeEnum key)
{
if (_dict.TryGetValue(key, out var value) && value is T)
{
return (T)value;
}
Debug.LogWarning("key value does not exist of " + key.ToString() );
return default;
}
public IEnumerator<KeyValuePair<StatsInfoTypeEnum, object>> GetEnumerator()
{
return _dict.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _dict.GetEnumerator();
}
}
The problem is that is quite a lot of work to get values (statsInfoDic.GetValue<type>(StatsInfoTypeEnum)) so right now I have started to build a wrapper class that basicly does things like this:
public class Stats
{
public StatsInfoDic statsInfoDic;
public void Add<T>(StatsInfoTypeEnum key, T value)
{
statsInfoDic.Add(key, value);
}
public T GetValue<T>(StatsInfoTypeEnum key)
{
return statsInfoDic.GetValue<T>(key);
}
public Stats()
{
statsInfoDic = new StatsInfoDic();
}
}
And I started adding functions like this:
public Faction GetFaction()
{
return statsInfoDic.GetValue<Faction>(StatsInfoTypeEnum.faction);
}
The question is if there are any better ways around this or do I need to add this for all my enums? I could of course do something like GetString, GetFloat etc but wondering if anyone has done anything similar and come up with anything smarter
Would statsInfoDic[StatsInfoTypeEnum] works for you ?
Yeah that would work really well I think
Then you can use indexer. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/indexers/
However, you will not be able to return generic type like you are doing, instead I suggest that you return an object such as Statistic that will be implicitly cast to the type you want
In other words, something like.
Dictionary<StatsInfoTypeEnum , Statistic> dict
this[StatsInfoTypeEnum type] => dict[type];
public class Statistic
{
public static implicit operator float(Statistic s) => s.GetValue<float>();
}
It really is just something I would try.
I did once something similar but it did not fit my needs.
Great, reading up on it now, havent used it before
Also, the reason why it did not work for me is because I had to feed parameters (Context, because of my statistic are context aware) to my GetValue which is not possible with implicit conversion.
However, down the line, I feel it was a mistake to make them context aware so I would suggest to not do that (-do not make them context aware-).
Thanks so much, great to get some feedback. Im not that experianced and havent really built that much around generics before so really valueble with input
hello, im having trouble in my game using navmesh. im making a city builder that uses navmesh, but the map is quite big, there is also verticality with bridges and otehr things of the type. i cant find a decent way to add walkable navemesh areas after i create a bridge. is its possible to make update the navmesh winthout rebaking everything?
navmesh surface you can bake them individually
? i dont undertand its possible to break the navmesh in to smaller ones and bake them individually?
yes of course, they also can be sectioned off into specific areas / volume
can you give the component name or functions that can do that?
I just told you lol Navmesh Surface component, then look at the different modes of baking / collecting objects to bake
oooh ok
Go to YouTube, you will get many tutorials , will make you understand easily
Source generator dll's stored in the Assets folder are not supposed to apply to to assemblies in packages right?
What does "apply" mean in this context?
And by "package" do you mean "assembly definitions"?
I'm trying to use this source generator:
https://github.com/EngRajabi/Enum.Source.Generator
It generates an attribute, but it seems to be generating it for the default assembly and assemblies from other packages because I'm getting a type conflict on the attribute that it generates which is pointing to the package assembly
Assets\Behaviours\Systems\Input\Panels\DEPInput.cs(10,6): warning CS0436: The type 'EnumGeneratorAttribute' in 'Supernova.Enum.Generators\Supernova.Enum.Generators.EnumSourceGenerator\EnumGeneratorAttribute.g.cs' conflicts with the imported type 'EnumGeneratorAttribute' in 'AsyncImageLoader.Runtime, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'Supernova.Enum.Generators\Supernova.Enum.Generators.EnumSourceGenerator\EnumGeneratorAttribute.g.cs'.
What I mean by "apply" is that the source generator runs for that assembly
At this point, I may just fork it and manually define the attribute
https://docs.unity3d.com/6000.0/Documentation/Manual/install-existing-analyzer.html
ny scripts that are within the same assembly definition as an analyzer are in that analyzerโs scope. For analyzers in the root level of the Assets folder, Unity considers all files in the project to be in scope
Yeah I saw that, but didn't think it would apply to packages folder as well
I had to fork and modify the generator anyways, since it isn't configured for Unity
Im working on a project that is a 3d modeler kind of like inventor assembly, but with specified parts instead of making your own; like certain sizes of metals. One feature that my friends are trying to add is an ability to create custom parts. But these custom parts are only made with like a plastic sheet. so they are like 1/8 inch thickness but any shape you want on a plastic sheet. (image for example).
i feel like this has been done before and wondering if there is any documentation on it?
Another solution would be to have the user import .svg, .fbx. or .obj files but i havent found any ways to do that yet. If someone could help me with that it would be super appreciated.
What are you asking though? ๐
Project seems cool
Are you asking how to implement the custom sheet?
And would players make the sheet ingame or in an external software?
so i have 2 options for it, either they make the sheet ingame, which really i just mean like they trace out some design they want and then it gets expanded into 3d but only 1/8 in long.
or the second option they can just import their own 3d model they made on like inventor or something
if you want to try the project you can download it here, https://github.com/BreadSoup/Protobot-Rebuilt/releases/tag/v1.3.5
You could probably use a third party solution for importing 3D files at runtime.
For in game editing, I would make a simple UI editor that lets you draw lines, drag vertices etc. It's very much doable
okay, though ive tried looking for third party solutions and i just cant find anything. atleast not in runtime.
and for the in game editor, ill have to look into that, i havent experimented with stuff like that
First one that I found, costs 20bucks though
https://assetstore.unity.com/packages/tools/modeling/trilib-2-model-loading-package-157548
Seems like it would work at runtime
You can always write your custom importer too if you want to.
hmm yea thats what we do a lot of the time, but like the scripting API is the difficult part.
i mean writing our own is better but does unity have that built in?
unity has a SVG importer (for 2D shapes) and importers for common 3D poly mesh formats, typically for runtime import you want to use gltf, paid and free import assets exist.
you likely want to be able to import shapes made with 3rd party tools that you only arrange in your unity tool.
why is this not working?
public static async Task LocalPosRoutine(Transform transform, AnimationCurve curve, Vector3 startPosition, Vector3 endPosition, float duration)
{
transform.localPosition = startPosition;
transform.gameObject.SetActive(true);
float et = 0;
while (et < duration)
{
et += Time.deltaTime / duration;
if (et > duration) { et = duration; }
float eval = curve.Evaluate(et);
transform.localPosition = Vector3.LerpUnclamped(startPosition, endPosition, eval);
if (et >= duration)
{
transform.localPosition = endPosition;
break;
}
}
await Task.Yield();
}```
define "not working"
but at a guess, i'd say you're probably doing something like using Task.Run to start this which means it is scheduled to run on the threadpool which may not be the main thread, so when you try modifying a unity object the thread silently fails because you cannot use the majority of the unity API off of the main thread
You are yielding outside the loop
So all of the while loop iterations happen at once
But yes, be explicit about what is not working
Im not using Task.run.
the function is running fine as a coroutine, but when i changed it to a task, the tranform is no longer interpolating.. instead it's just snapping to it's end position instantly
also note that awaiting Task.Yield does not guarantee that it waits for the next frame. if you're on unity 6 you should be using the Awaitable class to await the next frame
how could this be a problem?
if the system decides to continue execution multiple times per frame then you'll get more iterations of the loop than you'd expect. or if it doesn't continue execution for several frames then you'll get fewer iterations. and Time.deltaTime is not the difference in time since the last iteration, but the difference in time since the last frame so those extra long/short yields would end up with weird behavior
so what you said fixed it but now i'm getting some other weird snapping like it's not fully running the while loop but ending on the correct position.. this is the function that calls it.
{
List<Task> tasks = new List<Task>();
int delay = (int)(iterationDelay * 1000f);
foreach (var transf in diceComps)
{
Vector3 start = transf.transform.localPosition;
Vector3 end = transf.transform.localPosition;
start.y -= 500f;
tasks.Add(TransformUtility.LocalPosRoutine(transf.transform, curveDiceMove, start, end, duration));
await Task.Delay(delay);
}
await Task.WhenAll(tasks);
}```
anything wrong with this function?
the iterationDelay can be any float i want it to be and works fine.. but the duration variable only works if it is set to 1 sec...?
You're adding all commands to 'move' as their own tasks without actually moving them within the loop. Then it does it all your "move commands" at once when you say Task.WhenAll(tasks). It doesn't actually move anything during your loop
but it's working as intended ? i'm confised by what you are saying
It moves it to the correct position in the end but doesn't move smoothly right?
Could you link a site for the 3D importers? Like the scripting api?
it moves smoothly at 1sec duration but anything less than that it snaps out early
I'm not really sure what you mean though.. ? i am running the localposRoutine in the loop and i have the delay set correctly?
Thatโs the thing tho youโre not running it youโre simply adding the delegate to a list
so instead of tasks.Add(TransformUtility.LocalPosRoutine(transf.transform, curveDiceMove, start, end, duration));
do this? Task t = TransformUtility.LocalPosRoutine(transf.transform, curveDiceMove, start, end, duration); tasks.Add(t);
I don't want to wait until it's finished... i want to wait for the delay timing only
So you want to delay it then move the next component?
Right now none of your move commands are done until all the components have been delayed for
? the components are moving at the correct time they are supposed to move.. the issue is the Task is cutting out early for each one.. like it's clipping out early. lets reset for a second to make sure we are on the same page. do you understand what i'm saying now?
litterally the only issue that isn't behaving properly is when i adjust the "speed" at which this whole things happens.
No thereโs a fundamental flaw in your code. When task.Add(awaitable task) is called it simply schedules it to be run at some point. It may be run right now or anytime in the future itโs up to the scheduler. When you call Task.WhenAll() it actually does the commands, but since this function is async it finishes at any time relative to the game loop
You want to call move directly not queue it to await at once
ok so i have a misunderstanding of how the task works...
how do i acheive what i want to without having to wait on each one indipendently to finish?
If your code works itโs simply a fluke and should not be relied upon
got it, ok so how do i acheive what i need to?
You want each component to wait an incrementally longer time? So like dice 1 waits 1 second and dice 2 waits 2 or do you want them all to wait 1 second and move?
i want the move animations to overlap.. so all of them are happening incrimentally but happening simutaneously for the bulk of their animation
Assuming localpositionroutine spends duration to move the input, the fix is to not add the extra delay
for example:
all dice have the same animation duration lets say 1sec.
but their is also a itteration offset delay. lets say its .5 sec.
dice one goes. wait .5 sec then send dice 2. when dice 2 starts, dice one will be half way done with its own animation.
i'm trying to create a pure function that i can use for other elements of my game. a function that serves multiple purposes, wether it's dice, or menu UI button animations etc.
is there a particular reason you switched from using coroutines to using tasks for this? coroutines can do what you are attempting much more easily and are actually intended for time/frame specific waiting unlike tasks which aren't exactly suited for what you appear to want
coroutines are specific to monobehaviour scripts correct? i want my functions for this to be reusable in projects. so a couple of my functions are static, ones i will reuse for any project
Make a new async function like this
tasks.Add(async () => {await Task.Delay(delay); await TransformUtility.LocalPositionRoutine(โฆ);})
Sorry Iโm on a mobile device itโs really hard for me to type code
Then await all these tasks at then end using Task.WhenAll()
you can do the exact same thing as a coroutine. it's just that a monobehaviour has to start the coroutine. that doesn't mean the coroutine method must be declared on that monobehaviour
doesn't this put a delay first also?
Just set delay to 0 in the first one
i understand that, but i need to call the coroutine outside of the monobehaviour.
so why can't i ad the delay at the top of my forloop?
Youโre delaying when your movement is being added to the list not when itโs executed
this is easily done too. but it seems you don't care and just want to use tasks. so good luck ๐คทโโ๏ธ
why are you saying i don't care? I'm coming here to ask for help. if what i'm saying is wrong, you have the choice to correct me, or stay out of the discussion. don't tell me i don't care.
why is their a double await? idk how tf you guys figure this out. this makes no sense to me
also it won't let me use the lambda function to make it
Sorry itโs an accident Iโm typing on a phone in the rain ๐ญ
Idk why not but u can make a local function u define inside ur function
async Task diceMove(){}
it is trivial to just have a DDOL object with a MonoBehaviour on it that you've got a static reference to in order to start the coroutines
and you would get the benefit of actual proper frame timing instead of what i described earlier regarding Task.Yield.
or switching to using unity's Awaitable class (if you are on unity 6) would lead to better results with your current code
can i break this down a bit more.. idk why but i feel like i'm not understnding and their might be a miscomunication on my end.
this is what i'm trying to acheive, forget the animation stuff for now.
- a coroutine to handle 1 single animation.
- a coroutine that takes in an array of transforms and the a coroutine (the number 1.) and assign it to each transform with a delay between all of them. ex. (Transform[] transforms, Coroutine/Task routine/task, float iterationDelay)
So you want to perform the same coroutine on several objects in a sequence
And be able to pass the coroutine into the second coroutine as an argument
exactly. but i want it to be a pure function that i can reuse in any project
my reasoning for wanting it this way to to be able to pass in new "animations"(coroutines) to the same function for different aspects of my game or multipe games
I've made this Coroutine function many many many times. and i'm tired of remaking it. so i figured Tasks are the only way to go since i can store it statically.
@hexed pecan
Uhh there might be a better way of going about this but this is what came to mind...cs void Play() { Transform[] targets = ... StartCoroutine(AllAnimsCoroutine(targets, t => AnimCoroutine(t))); } IEnumerator AnimCoroutine(Transform t) { /* Do stuff */ yield break; } IEnumerator AllAnimsCoroutine(Transform[] targets, Func<Transform, IEnumerator> coroutineGetter) { foreach (var target in targets) { IEnumerator coroutine = coroutineGetter.Invoke(target); yield return StartCoroutine(coroutine); // Waits for the coroutine } }
So passing in a Func that gets the coroutine for that transform
Could be generic too instead of using just Transforms
so do this work in a way to make it static?
and how would i be able to have my game state waiting for all routines to end?
that code, as written, could not be made static because it is calling StartCoroutine on this, but as i said before, it's incredibly trivial to just spawn an object that you slap a monobehaviour on to use for starting the coroutines
I sometimes do use a singleton that runs coroutines that aren't attached to a particular gameobject
I'm trying really hard to make a clean setup for this since i use this type of thing often and in almost everyone of projects... there is not other way other than to create a singlton or DDOL object?
@hexed pecan
If you use coroutines, you need a monobehaviour, that's it
if you want to use a coroutine then you need a MonoBehaviour. that is not negotiable.
if you want to use async methods then you would ideally use unity's Awaitable over Tasks so you have the proper control over the execution timing that you want
Btw you can make a singleton class that just instantiates a singleton instance when accessed, if it doesn't already exist
and btw, i don;t want people to think i'm just trying to get all the code written for me. i'm trying my best to understand this fundamentally so i can iapply this knowledeg to alot of other things in the future without having to ask for more help
So you don't have to place it in the scene beforehand
i'm aware of how to make all this work the way you have been showing me. I'm just looking for a more scalable solution
is there any guide about using namespaces to reduce domain reloading?
Can anyone help me with this issue? I'm using tilemaps for the first time to layout the map. I have the red tiles set to have a collider and the blue one (top left) and green one (bottom right) to not have colliders. I'm trying to send raycast out to detect if the user hit a wall. however, I need to assign certain tiles a layermask. Right? How do I do this?
yes, that guide would be: namespaces have no impact on domain reloading.
it is the number of static objects in each assembly that is being reloaded that determines the time domain reload takes. split your code up into different assemblies and only the ones that have changed will be reloaded
this is not optimal, hasn't been tested, and was written in notepad++ so there may be issues, but theoretically should work for what you are trying to do (you'll obviously need to add the correct using directives, i was too lazy to do so)
https://paste.myst.rs/fp0w8328
it's based on what Osmal posted before, and even includes a callback for when all of the coroutines have completed. you can then build on this to do more than just start a bunch of coroutines in sequence
would I create a class for projectiles that contains such variables and Booleans such as damage, isexplosive, speed, dropoff, etc and access them in the script of which instantiates the projectiles or would for a global bullet variables or is it a waste to do such and I would instead just include these in the class of which instantiates the projectiles?
Guys i am using playerprefab to save data i want to save data for scene 1 when i go to scene 2 and when i come back to scene 1 it loads
how do i do that?
This depends a lot on your project and context and even just preference.
If you have many bullet types that each weapon can use, I'd say have a separate data structure for it.
everytime i try it doesnt worlk
- save on scene exit
- load on scene entry
As simple as that
how do i write it
You'll need to elaborate on that
private void ???
how do i write that
You can see the api in the docs
You're not gonna get a complete solution here
At least show some effort
There are many resources online on how to do that.
i acctually searched
and did
this is my last effore
i came here as a last choice
preferably I would have different projectile types which includes but is not limited to isexplosive boolean and the radius, damage, duration that goes along with it (if true) and I would also have a damage, speed, dropoff, gravity, etc (if isexplosive is false), so maybe a separate data structure would be good to have
sorry for the lack of context
Then share your setup and explain what didn't work. Ad well as how you debug it.
Yeah, sounds like a separate script would be fitting. Maybe an SO.
i use sometheing like that for close application and open application private void OnSceneUnloaded(Scene scene)
{
// Save the game data before leaving the scene
SaveGameData();
i want to use it for scene entry Load Scene exit Save
You'll need to call that before you start loading a new scene. As for how and where exactly, that depends entirely on your project(and where you load scenes in code).
As for loading, you can do that in awake or on scene loaded callback.
I have never really used SO's before, would they work roughly the same as making another class for the projectile?
Yes. It's basically like a MonoBehaviour, but can live outside objects and scenes as an asset in the project.
sweet
So you can define many different bullets scenes with instances of the class.
nice, I'll look into it, Thanks Dlich as always.
what does it mean by this ?
An object reference is required for the non-static field, method, or property 'CoroutineManager.Mono.StartRoutine(IEnumerator, Action)
ah, it's probably because i named the property the same as the class, change one or the other
Mono isn't a good name for it anyway, so i'd recommend changing it to something more descriptive
is it because this Mono.StartRoutine should be named _mono.StartRoutine
no, you need to use the property
this is throwing the error
Mono.StartRoutine(InSequence(objects, routineGetter, delay), onComplete);
i am aware. and i've told you how to resolve that
i'm just not sure what part you are talking about... what is mono in "Mono.StartRoutine(InSequence(objects, routineGetter, delay), onComplete);" reffereing to?
the reff is private static Mono _mono; but i should change Mono class to something else?
it should be the property, but as i've pointed out i named the property the same thing as the nested class so it's trying to use that directly instead
again, you need to use the property, not the field.
are you just unaware of what a property is?
yeah what property are you talking about. it's not that i'm not listening to you, i just don't know what you are saying
the one on line 4. did you just not read the code or what?
is Mono something that already exists in Unity boilerplate code or something?
alright so you just copy/pasted the code without reading it. that's good to know
no i didn't actually, i read the code for 5 min trying to understand it. then i realized i have to go, so i copy and pasted it into my vscode. to look at later but their are a ton of errors. im just asking what's wrong with it
and let me guess, those "ton of errors" are that one error and then a bunch of errors about missing a using directive because i already told you that i did not include those
i already told you how to resolve this issue though, but you didn't bother reading the code so do whatever you want with it ๐คทโโ๏ธ
bro, there wasn't a ton of errors. my bad, there were 3 and 3 or 4 missing directives. but anyways man. thanks for the help
have a great night. i gtg
i think line 4 you are reffereing to private static Mono Mono => EnsureMonoExists(); yeah i already changed that but there is still an error that you clearly aren't reading from my end.
oh of course, i'm supposed to read your mind to know you've changed something?
What is the different between update and fixedupdate, I was looking for how to implement addtorque and they say I should use fixedupdate instead of update, why ?
Update runs every single frame. FixedUpdate runs at a fixed timestep that is in step with the physics engine. It is typically best to perform all physics operations inside of FixedUpdate so that those operations are performed along with physics updating and so they are performed on a fixed timestep
Even with movement ? Should Transform.translate or transform.position be used in FixedUpdate ?
neither of those use physics
in fact, if you want an object to interact with physics correctly you shouldn't use either of those and should instead use a rigidbody (or a character controller if you only want it to react to colliders in its movement path)
Such as rigidbody addforce or velocity ?
yes, both of those interact with physics
And everything which use rigidbody is physics so I should put them in the fixed update ?
all of the rigidbody methods yes
Is it necessary to use time.deltatime in fixedupdate since they use physics based instead of framrate based ?
it depends on what you are doing
You don't particularly need to use delta time in fixed update, since it's always fixed. You can use it in some cases to standardize values, like speed, so that it's in per second space rather than per fixed frame.
I was trying to get the ball moving like this, should I add time.deltatime ?
no
No, as you're assigning it to velocity.
Hey , I am trying to manage my async processes with UniTask. In the UniTask tracker, the process is always pending, if I exit gameMode, only then it completes. I can't find anything to block the code.
Any idea ?
public static async UniTaskVoid LoadSceneAsync(int sceneIndex, Action<float> onProgress = null, Action onComplete = null, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
AsyncOperation operation = SceneManager.LoadSceneAsync(sceneIndex);
if (operation == null)
{
ELog.LogError("Scene Loader", $"Failed to start loading scene with index: {sceneIndex}");
return;
}
operation.allowSceneActivation = false;
try
{
while (operation.progress < 0.9f)
{
cancellationToken.ThrowIfCancellationRequested();
Debug.Log($"Progress: {operation.progress}");
onProgress?.Invoke(operation.progress);
await UniTask.Yield(cancellationToken);
}
onProgress?.Invoke(1f);
operation.allowSceneActivation = true;
await UniTask.WaitUntil(() => operation.isDone, cancellationToken: cancellationToken);
onComplete?.Invoke();
ELog.LogInfo("Scene Loader", $"Successfully loaded scene with index: {sceneIndex}");
}
catch (OperationCanceledException)
{
ELog.LogWarning("Scene Loader", $"Scene loading cancelled for index: {sceneIndex}");
}
catch (Exception e)
{
ELog.LogException(e);
}
}
SceneLoader.LoadSceneAsync(1).Forget();
What "processes" are you talking about?