#archived-code-general
1 messages · Page 234 of 1
You can DIY faster per frame loops, but I really wouldn't worry about this too early
My plan was to just have it be a visual indicator of its hp, with possibly some animations when it changes for now
So with an event, I'd just add a listener to the event from the player's hp script with no update right?
And then have some function that renders the new hp UI
For some reason I was conflating update with monobehaviour, I guess it makes sense for it to be a mono behaviour but simply not have an update
Your hp script should have the event, and one method that is used for changing its health. In that method, you invoke the event with the new hp as a parameter
You can invoke it with the old hp and new hp if some other systems need to know the old one, or the difference
Whatever script is handling the UI would subscribe to the event on the player hp script
Heyo, Ive been searching on this topic for quite some time now and I am close to saying "this doesnt work. dont waste your time!". I am working on a game in which the character has to be able to pickup multiple items and have multiple animations for holding these. I thought it would be a smart idea to make my own editor extension in which I use a selfmade FK algorithm to use collision checks to wrap the hand around an object. All of this stuff works. The problem now is that Im unable to capture the pose and to write it into a humanoid animation. I need to blend animations in the end. I dont want to have a generic animation for the entire rig only due to the arm movement being a completely seperate thing. I have tried many things to capture the pose of all the hand transforms to turn them into a keyframe for a humanoid animation, but non seem to work for me :/ I hope someone else could shed some light onto the hole topic.
Does Animator.StartRecording and such don't work?
https://docs.unity3d.com/ScriptReference/Animator.StartRecording.html
Hmm. Nevermind. It's not what I thought it is.🤔
Maybe this would work:
https://docs.unity3d.com/ScriptReference/Animations.GameObjectRecorder.html
Only in the editor though.
Why the following two pages were deleted from Unity documentation?
https://docs.unity3d.com/Manual/nav-CouplingAnimationAndNavigation.html
https://docs.unity3d.com/Manual/nav-MixingComponents.html
because that info has been moved to the relevant package site
https://docs.unity3d.com/Packages/com.unity.ai.navigation@2.0/manual/MixingComponents.html
Oh, thanks
Hey guys,
The type or namespace name 'HmsPlugin' could not be found (are you missing a using directive or an assembly reference?
I got this error but the problem is I actually do have HmsPlugin .-.
IDE sees it and everything, its just when I'm trying to build addressables?
So the problem I have is, I want to play a sound when a gameobject gets killed, but when the object is destroyed so is the audio, what is the way to get around this issue?
PlayClipAtPoint
That worked
Working with rigidbody movement. Everything is fine except camera movement. Anyone know why its jittery?
playerCamera.position = player.position + player.transform.up * 0.5f;
I tred Update, FixedUpdate, LateUpdate and the rigidbody is interpolate
Okay nevermind for some reason positioning it at a transform that's a child of the rigidbody makes it better
You probably don't have interpolation turned on for your rigidbody and/or you are moving the camera at the wrong cadence
It was interpolate and I tried all the updates I mentioned but moving it to a transform that was a child of the rb worked
I'm just mentioning because if you set it up properly it doesn't need to be a child.
It also depends on how your script works etc
You mention that I just tried moving to the rigidbody's transform's position rather than the rigidbody's position and it seemed to work
I didn't know they were different
they are super different
rigidbody interacts with physics system, and writes to transform (frequency depends on interpolation mode, I think)
moving a transform does NOT move colliders. Moving rigidbody position does
transform.position += Vector3.one;
Debug.Log(collider.bounds.center - init); // this is 0,0 ```
rigidbody.position += Vector2.one;
Debug.Log(collider.bounds.center - init); // this is 1,1 ```
for camera movement, I normally use a kinematic RB on the camera, with rigidbody.MovePosition, and interpolation on
.MovePosition queues up a rigidbody, so next physics simulation, physics will tell RB to move smoothly from point A to B. It is planned to reach point B at start of NEXT FixedUpdate after that. Physics system will smoothly change the transform as it goes along
make sense?
Halo guys. Asking about voxel data. I'm using struct Block. For context i'm making an autotile level design tool. Some of the calculations are stored in each Block, which includes multi array like public int[][] Compatible; (for each tile type, for each direction)
This is WFC but made into a sparse graph using dictionary
My question is, I will need to init the existing collection of Block, and u gotta make a copy, init the arrays, then set it back in
Wouldn't this make wasted allocations upon get block, init array, set block? The tool is editor only for now but some functions will be for runtime in the future
Maybe the central autotile processor should keep track of these helper arrays, which is what the original algo does. I thought moving these to each struct Block would make things more easier to read but, basically if someone would throw a rock at me for storing big arrays in struct and modifying it n setting to the collection all the time, i'll rework it
Or actually when i do Compatible = new int[n][] in a Block, this is actually a reference so when a struct is getted, ref types members of the struct are not "copied" all the time in memory?
The details of all this are quite important, but it should be pretty clear that when you use new you are allocating a new array. Such as new int[n][]
Do you need jagged arrays here btw? Or would a multidimensional array work?
It's a jagged array, each layer is for something different. It's not like [x][y]
WHy not have separately named arrays for each thing then?
are you getting much benefit from a single jagged array?
Block b = new Block();
b.Compatible = new int[5];
blocks[pos] = b;
Block c = blocks[pos]
c.Compatible[0] = 42;
blocks[pos] = c;
In this case memory wise, b.Compatible and c.Compatible is the same thing right?
The OG algo does a lot of bulk array operations using several helper arrays for mapping, and this eases the various loops
This is only 1 of several arrays
Ok2 cool that's good then
yes they are both references to the same array
Hello
I seem to be having problems with a coroutine
public void PlayerReflected(InputAction.CallbackContext context)
{
if(currentState != 2)
{
return;
}
if (context.performed && !MissionLog.GetInstance().isUpdating)
{
currentState = 3;
StartCoroutine(MissionLog.GetInstance().UpdateLog("Reflect bullets back at enemies"));
if(spawnCoroutine == null)
{
print("No");
spawnCoroutine = StartCoroutine(SpawnEnemies());
}
}
}
IEnumerator SpawnEnemies()
{
while(PlayerManager.GetInstance().vialPoint != PlayerManager.GetInstance().vialMaxPoint)
{
print("Yes");
// if(tutorialEnemy == null)
// {
// tutorialEnemy = EnemyManager.GetInstance().SpawnEnemy(0, new Vector3(3, -10, 0));
// }
}
PlayerKilledEnemies();
yield return null;
}
Whenever the playerreflected is triggered
the game jsut crashes
Im not sure why
You have a pretty obvious infinite loop
In the spawnEnemies?
yes..
you have a while loop that doesn't change anything inside it related to the conditions
it will run forever
hence crashing your game
I was considering that to be the problem but i didnt think it would crash the game if it just print lol
of course it will crash the game
Im tryna make it so that the coroutine would constantly spawn enemies whenever the player kills one
there's something you need to realize about your code in Unity. While your code is running, the entire game engine is paussed waiting for your code to finish running.
If your code doesn't finish running, the game is frozen forever.
Alright
for starters you could drop a yield return null; into your loop so it takes a break every frame
This is what I want to do but when I remove it
It causes an error
- why do you want to remove it?
- what error?
Hold on im removing it so i can copy the error
right now you have yield return null at the very end of the coroutine, which is pointless
thre's no need to remove it
Oh u mean put it in
put it INSIDE the loop
Oh
I misread
mb
ok wow
I get how it works now
thx
Another question:
If I assign a variable to a gameobject
and later on i destroy the gameobject
How do make the variable return to null
variable = null;
however - variable == null will already return true for a destroyed object
but cs Destroy(variable); variable = null; would be a good practice in general
The problem is that the variable is only gonna be used on this scene
cuz its a tutorial
I don't really know what that means or why it's a problem
variables live in code, not in scenes
Cuz if I write the variable = null in the OnDestroy function, the variable might not be there in other scenes
Maybe tell us exactly what the problem is and show some code
this is all extremely vague. Without specific details, code, etc, we have no idea what you're talking about
what its in the script
variables don't live in a scene
Alright so let me just give the current situation
So I have an enemy script that is gonna be the base for all enemies in the future but at the moment we are planning to use it for the tutorial. In the tutorial there is supposed to be an event where we would spawn one enemy, wait for the players to kill it, then spawn another one.
Initially, in order to make sure that only one enemy spawns and only when that enemy dies would another enemy spawn, I make it so that when the enemy is instantiated, I assign it to a variable. The problem is when the enemy is killed and the gameobject is destroyed, the variable does not return to null. This is a problem because the way i prevent multiple enemies from spawning and spawn a new enemy is by checking the the variable is or is not null.
I could change the code of the enemy behaviour by adding that on Destroy on function, but the variable that the enemy is assigned to might only exist in the tutorial manager's code and nowhere else; therefore if I were to add a variable = null in the onDestroy function and if the tutorial manager is not there, then I am afraid it will cause some issues.
Comparing a destroyed object to null does work. If it doesn't work in your case then you have some other issue in the code.
when the enemy is killed and the gameobject is destroyed, the variable does not return to null
enemyVariable == nullwill absolutely work
anyway in general the approach to this is to have some kind of centralized EnemyManager or something, and have the enemies notify the enemy manager when they spawn and when they die.
rlly? hmm, maybe ill double check the code later
I found another way around it but i found it rlly odd
ye that sounds like a good idea
in general it's not that odd. It only works due to some Unity magic. But normally you cannot expect variables to "become null" unless you explicitly set them to null.
Alright alright
Thx
Ill try to improve my code with the enemy manger later one
Also I have one last question
Atm the player code is divided into two due to some msicommunications with the team
One code manages stuff like movement and controls wehre as the other handles health and stat points
Do u think it is better to jsut merge it?
not necessarily
probably better to have that as two different components
Each script should generally handle "one thing"
Movement might be one thing.
Stats may be another
Alright
thx
Cuz i heard from a teammate that we should minimize scripts in unity?
to make it less slow
they're wrong
Ok then
what you do with the script is far more important than how many scripts you got
He said that he wanted to create an enemy manager that manages every enemy's movements
And Im not experienced with unity
But that sounds very wrong
yo i have a problem is anyone able to possibly help me
this is pretty common actually
int[] directions = tile.GetDirections();
Debug.Log(tile.Visible);
if (tile.GetVisible() & directions.Length != 6)
{
so both of these should return .GetComponent<Renderer>().isVisible, however they always return false... even if I can literally see the object
No / Depends on how it's implemented
Interesting
I still have a lot to learn then
Do u have examples of games that uses it and games that do not?
No, sorry.
It's fairly common though. Someone else may have examples
Consider this though. Unity loops through every update and runs them in sequence already
Ye thats true
Just a tip: you're nowhere near the level where you should be thinking about how design affects performance. That comes much later. For now just focus on finishing a game
Alright thx
You need to show the method/property
ask the question, Don't ask if you can ask.
I figured it out, it was actually running so fast (which I didn't expect) that it genuinely wasn't visible for that frame
okay so basically I am having errors in my unity console and It wont let me play the game at all
btw im a massive beginner
its this
when i click on it it references the line of code which has the problem but i dont know what to put
this is the line
the first two means you're missing a ;, probably at the end of the line
and this
ah okay
Your !ide looks oddly unconfigured
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
• Other/None
the second two is that your parameters don't have types
it says this now
You need a functional IDE to program properly
ah okay thx i will do that
mm doing that will help a ton
okay ill quickly do that and come back
Also, you shouldn't multiply mouse input by deltaTime
all of these are that you've put whatever ' ' is in the wrong place, either you've added one or don't have it. The IDE being set up will make that super obvious imo
ah okay
why, what does it do
ah thankyou
okay im gonna use vs studio community instead of vs code
what do the logs say?
When you do something like Debug.Log(intervalTimer); you should really do Debug.Log($"Interval timer: {intervalTimer}"); to make the logs more clear
Ok turns out I forgot to make the player mortal so the damage works fine
It still runs far too fast though
what do the logs say?
also it sseems like you're doing frame counting here for some reason
instead of time counting
intervalTimer++ per frame means you're counting once per frame, in other words, all your things are expressed in terms of frames rather than in terms of seconds
And this... if((intervalTimer % interval).Equals(0f)) is... kinda silly
what you want is something more like this:
float timer = 0;
float timeRemaining = duration;
while (durationRemaining >= 0) {
timer += Time.deltaTime;
while (timer >= interval) {
Damage(damagePerInterval);
timer -= interval;
}
timeRemaining -= Time.deltaTime;
yield return null;
}```
notice the use of deltaTime which means we're working in seconds, not frames
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class AttackRangeTrigger : MonoBehaviour
{
public UnityEvent<Collider2D> OnAttackRangeTriggerEnter;
public UnityEvent<Collider2D> OnAttackRangeTriggerExit;
private void OnTriggerEnter2D(Collider2D collision)
{
OnAttackRangeTriggerEnter?.Invoke(collision);
}
private void OnTriggerExit2D(Collider2D collision)
{
OnAttackRangeTriggerExit?.Invoke(collision);
}
}
i get an error here, saying UnityEngine.object cant be converted to UnityEngine.Collider2D
is there anything wrong here that one could spot instantly?
On which line?
18
which is?
the one in the last funciton
likely due to an invalid configuration of a listener in the inspector
here?
i thought the invoke function passes the argument
It does if you assign the function from the dynamic parameter list
you have assigned your function from the static parameter list
and have set None as the parameter
and what do you mean exactly when you say, dynamic parameter list
in the dropdown
if there's a function that takes a Collider2D, it will show up under "Dynamic"
Do yall have a Microsoft visual studio? is it really important?
Solved! thank you very much
A proper code editor of some kind is very important, yes
Rider or Visual Studio are the best
This works, thank you
Thank youu
PraetorBlue can I ask why you spend so much time helping people here
Like, is it your job? Do you work at Unity?
This is where I go to procrastinate from doing my real job, which has nothing to do with Unity, no.
why does the first one work but the second one doesnt ? i just want to controll the emission of a particle system
Intricacies of properties and structs in C#
In this particular case the compiler happens to be over cautious and it would actually work, but that's because Unity set this up in an unusual way
yeah, it's a really funny situation
Structs are value types, so you always get your own copy of them. barrelSmoke.emission is a property -- a method that looks like a field. The method returns a struct, so you get a copy of that struct. Assigning to that copy would be pointless, and the compiler complains.
But these structs also have properties on them. When you set one of the properties, it calls some code to update your particle system. So it would work just fine.
It's very unintuitive.
thank you
If the struct actually held data, you would need to assign it back after changing its fields.
But it doesn't. It just knows how to get and set data from the particle system
I'm trying to assign an event handler to a Panel so that when it becomes active I can initialize the values of the components. VSCode complains about this:
Panel p = GameObject.Find("Date Time Panel").GetComponent<Panel>();
Saying that Panel is inaccessible due to it's protection level. I understand the error, but how can I accomplish this?
What is Panel?
Is that something you created?
That is not a built in Unity class.
If it's a class you created, you forgot to put public before it
Its what gets created when I use Unity editor to add a UI component to a canvas. I right click on the canvas, then UI -> Panel.
My research seems to Indicate that there is no such class in Unity, that instead what is created is a GameObject with a few other objects in it...
There's no such class
all that creates is a GameObject with an Image component on it
Panel is just the name of that option in the UI
Okay, so my UI is basically a series of panels and I turn them on and off as the user clicks through the navigation buttons. When one becomes active, I need to initialize the values of the various components.
I can't figure out howe to attach a listener to the GanmeObject so I can do something when it becomes active.
why not just reference the Transform/Gameobject of that object anyway in inspector
public GameObject ThePanel;
You put a script on it with OnEnable and OnDisable
Alternatively, just start whatever action you want to do from the code that is actually activating/deactivating them
Regarding this, it seems that when the panel is inactive, an attempt to find a component returns null.
GameObject.Find is not recommended for this reason among many others
Which is why I'm doing this
Okay is therer an alternative that will get me the reference when the panel is inactive?
You should drag and drop references to these things directly in the inspector
That's always the preferred method
https://unity.huh.how/programming/references
This has all the ways to reference things. A serialized reference (which us what Praetor is talking about) is prefered when possible
I didn't think the inspector gave me enough control. I have a UI that allows a user to change date abd time, and I want to init it with the system date and time when it becomes active
If it is initialized, it will return a reference. You can pass that wherever you need
Type myThing = Instantiate(myPrefab);
I don't see how the inspector would be any limitation here
Well I'm new to this, I guess I have to learn to use it better. But the UI init involves setting TMP_Text objects and Sliders to values I read from an asset.
Yep sounds like a very typical basic use case
make a script that has TMP_Text and Slider references
assign them in the inspector
and make an OnEnable function that populates them as needed
One function per script?
what?
Oh I guess I could use the same one and check for null
What are you expecting to be null?
If I have say 6 public TMP_Text variables, each one with it's own OnEnable script, I thought I need to populate 6 different fields for a script
wdym "eaqch with its own OnEnable script"?
Each one, when run, will only reference one of the TMP_Text fields, or so I thought.
public class DatePanel : MonoBehaviour {
[SerializeField] TMP_Text timeLabel;
[SerializeField] Slider slider;
void OnEnable() {
timeLabel.text = GetCurrentTimeAsString(); // you have to implement this "GetCurrentTimeAsString" function
slider.value = GetCurrentSliderValue(); // you have to implement this "GetCurrentSliderValue" function
}
}```
II would expect a script like this
for a single panel
You might attach it to 6 different objects if you want
Oh, I think i understand...
The scriupt is attached to the Panel with 6 fields... Not sure why I wa confused.
After years of writing code, I am struggling with this thing where part of the "code" is dragging references around in the editor and the rest is coding.
It's just a form of dependency injection
But in the Start() method, could I just do this.OnEnable(myMethod). ???
I don't understand what the intent of that would be or what you would expect that to do?
I would expect it to attach an event handler to the GameObject so when it is enabled it runs a function
OnEnable runs when it is enabled
there's no need to attach anything else
OnEnable is one of the special Unity functions
like Start or Update
Oh okay.
So what would everyone say is the best way to convert a Vector 2 to an angle 180degree or 360degree where I could also set the origin point (AKA the 0 degrees)
This is what I have for the pure conversion
{
float output = Mathf.Atan2(input.y, input.x);
return output * Mathf.Rad2Deg;
}```
So even easuer then? Just add an OnEnabled() and put my initialization cpde there?
OnEnable() as per my example
will check it out
Excellent, thanks VERY much, I appreciate tyour time and help.
Working perfectly, thanks!
Hello does anybody know what is wrong with this?
with what?
maybe
this code
ow this code yes
and i cant clear the console list
looks like you dont have your editor set up correctly
You use deltaTime with mouse input
oh it's vscode well I've no input for that except oh no
i talked to somone on here before about it and im not sure how to set it up correctly at all
!ide
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
• Other/None
so use visual studio instead?
never said that
oh okay
?? The link for vs code is right there
vscode is fine and I use it, but I don't have it hooked up either. ;p
is support still going for it?
how come you don't?
Not from Unity, yes from MS
I should probably look into it then. VS actually starting to be a little too much on my mem
more that unity is taking like 6 gigs now
i followed all the steps you said to set up the editor and i have already done them all
I am not sure if this is the channel to do it but I need help with my Game Scripting final
and everyone keeps saying its not setup correctly
Do you have red underlines in the ide?
no
hit the regenerate project files, and make sure vs code is selected as external script editor in external tools
Then you did not follow all steps
what is regenerate all project files
It is part of the guide
It's a button in external tools
Edit->Preferences->External Tools
it is not
One thing, do you have any error about a missing sdk?
i assure you i have i have read every word on that page and dont understand
It is shown in a picture I meant
can you show your external tools?
then i'd suggest:
- hit the regenerate button
- close unity, close VSC
open unity, then Edit->Open C# Project
okay im doing that now
if it's still not working then you did something wrong, did you install the vsc extension for unity?
no i havent
is that the problem?
Yes
then you lied about following the ide configuing steps
okay
no i havent i have the extension for unity in vsc
The Unity extension in vsc is what they meant though
oh yes i have that then
Yeah, they said it weird. You got it
wdym they
that is not related to the fact that your IDE is not configured
You
i dont know how to get that
ive followed all the steps and tried to do it for ages
Show the Visual Studio Editor package in Unity's package manager
Remove the Visual Studio Code Editor package.
But that shouldn't be the issue
okay
Oh, you may have the Engineering feature, which will prevent you from removing it
it wont let me remove anything
This is not the issue
oh ok
Yeah
#archived-code-general message
The engineering feature depends on it. Remove that to remove that package and update the other
actually maybe forcing a recompile (fixing errors) will fix the IDE if he has done all the steps correctly 🤷
what i was saying though is the fact i cant enetr play mode is because there is inherantly somthing wrong with my code
yes your code is wrong
True. Just comment out all the code and try to compile it then
but you need to configure your IDE anyway if you want to make your life easier
i have made an error in my code according to the console errors
There is a LOT wrong, yes haha
yes
damn i am such a noob ive not even done that much and screwed it
yes
It's fine! All minor stuff. You'll get it.
Just comment it all out for now
so i remove this engineering thing?
ye
alr
no, comment out your code
Yeah, you don't need it
okay ive commented it all out
Ok, now go to unity and let it compile
Ok, now regenerate the project files one more time? Not sure
okay
i click it and the button has the click animation when i click it but nothing appears to happen or change
now click Edit->Open C# Project
done it, it now opens vsc
Ok, uncomment your code and see if that worked
okay
If not, truly sorry, I just don't know
I can tell you part of the issue is missing semicolons on lines 14 and 15 though
#archived-code-general message
ah alr thx
ima uncomment it one file at a time
found these errors after uncommenting the inputmanager
oh shit thats cos i need the other files lol
Did you generate a c# file for your InputActionsAsset?
Oh, yeah probably that
Show line 24
Look at lines 14 and 15
But also, that is PlayerLook, the error is from PlayerMotor
Hello,
I want to move my project from one pc to another.
I have git initialized in my project, pushed and pulled the code, everything is fine.
Until I try to open the project on my other pc, there are prefabs with broken links, scripts missing from gameobjects etc...
Why is this?
Am I perhaps missing some essential cache files or something? This is my .gitignore: https://paste.ofcode.org/3JBGJynzD7j8weGczYvjsK
Should I un-ignore some files?
What else could be the reason?
Thanks in advance!
Oh, you also have a sentence outside any comment on lind 16 haha
oh
You have meta files in your gitignore
Should I not ignore those?
oh sorry the error from player motor went
they are all from player look
You definitely should not
should i just rewrite playerlook and start again
Why?
Just add the semicolons on line 14 and 15, and comment line 16
Okay, I will push the meta files then, hopefully it works. Thanks so much!
i have
there is still errors
Ok, show current code and errors
okay i fixed the bracket error
so strange
everytime i add a comma here an error goes
You should not have deltaTime in any of those lines there
what should i use instead
Nothing, just remove it
line 20 also
okay i only have these errors now
this is my code
not sure how to fix those errors
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
• Other/None
right now VSCode is not showing you errors etc
this is going to make it nearly impossible for you to work efficiently
i have done everything on that website i dont understand
which part you don't understand?
the fact that my ide wont highlight and work properly and i have followed all the steps
there are other steps besides installing stuff in VSCode
what is "everything"
i have seletcted everything it told me to in unity
all the steps on the website
We made sure the package is correct, the extension is right, it is selected in external tools, and clicked regenerate project files
yes
regen project files then and show output window
Also, they say there is no sdk error
okay
i click regen project files and nothing happens
you closed vscode and open the script?
yes
screenshot output windoow in vscode
this shows up
There is an sdk error...
You said there was none
That is almost definitely the problem
oh i feel so dumb lol
i was looking for the error in unity
okay im installing the .net thing
Restart your computer after
Yeaaay.
If you hover over those errors, they will explain and maybe give a fix
i still dont really understand the errors
Spelling errors it looks like
move is completely different than Move
I have changed the capitalisation of move and it is still highlighted
i have no clue
controller.Move
Not controller.move
yes that has worked
And that error you hovered over clearly says you can't have public there
So remove public
okay
should this vector be vector 3
because its not really referencing anything
You need to just do a basic c# course.
Almost every single error is just not knowing the language
https://www.w3schools.com/cs/index.php
Method declarations need a type. Not just the variable name
To be clear, there needs to be two words for each item (between every comma), not just one
alr
welcome to statically typed 🙂
whats that lol
the language you're trying to learn, in contrast to what you've done before
eg.
you need to specify types when you make vars
You need to declare and stick to the type. In pythod it is "dynamically typed" where it just guesses by context
its just that ive just started gcses and soon i want to use unity for once ive finished them
you cant just do
function (3,"string")
end expect it to know what u need
yea
you need function(int myInt, string mystirng) <- not real c# code : )
yes def
Okay so I have a statically managed ID struct. I want to keep it's functionality for other structs, without having to copy it over and over. Right now I am thinking of just
public ManagedID{
public int Value;
...
public struct MyID{
public ManagedID Value;
}
and then add proxy logic from MyID to ManagedID. I am not sure if this would break the whole use structs for one simple type thing. Like what is the size difference of a struct holding a struct holding an int, vs just a struct holding an int?
Is there a better way of doing this?
So your MyID struct is holding a object reference (conceptually a pointer) to the ManagedID (I assume this is a class?). So the size of your MyID struct is in no way affected by the size of your ManagedID object.
As far as a struct holding just a struct holding just an int, I would assume that each struct is the size of int in this case.
Ah sorry the ManagedID is a struct also
As I can't inherit from a struct wrapping it seems the best approach.
Otherwise I could make converters.
I think keeping the logic inside of MyID is better than having external logic that connects the two.
Ah yes, then if ManagedID holds nothing else but a MyID then it is the same size as MyID and therefore the same size as int.
Yes I agree, keep the logic in one place. I'm not entirely sure what you're trying to achieve but be careful of over-engineering what might be a simple solution.
So I googled and found out that you can’t create gameobjects in anything other than the main thread, so no multi threading or async, but how does that affect coroutines? Are they also not considered the main thread?
coroutines are on the main thread
Oo ok, I’ll have a play with those then
also there are tools like unitask and unity 2023's Awaitable class that allow you to use async/await easier
and the jobs system for some multithreading stuff too
Question for general, I know custom editors exist as a concept you can do. But is there a way without using one to like create sections to block out my inspector for scripts
regardless of what unity allows you to do, multithreading has a significant overhead.
unless you absolutely know what you're doing, you're likely going to make your program run slower.
the main bottleneck of unity applications exists in the random access nature of object oriented programming. dots fixes that, if you really need the speed.
Yes, depending on what you mean by "block out" - you can use the [Header] attribute to organize things, and [Space] attribute to add empty lines, both will be applied to the variable its used next/above, and you can also use [System.Serializable] on a class that does not derive from MonoBehaviour to display it, for example:
[System.Serializable]
public class Person
{
[Header("Basic Details")]
public string firstName;
public string lastName;
[Space]
public string job;
[Header("References")]
public GameObject prefab;
//etc...
}
public class SomeMonoForInspector : Mono
{
[SerializeField] Person someoneImportant;
}
You can also use public instead of [SerializeField] but with the latter attribute, someoneImportant can remain private and still show up in the inspector - the added bonus of using [System.Seriaizable] on a class as well, means you can collapsee itt in the inspector - beyond that, you may need a custom property drawer or Editor window
mmm that is what i was already using, was hoping there was at least subheaders or something
No subheaders that im aware of at least, though you can also make your own attributes with just a few lines of code, maybe that is what you might be looking for? For example, if you wanted to make an attribute to have a field as "readonly": https://vintay.medium.com/creating-custom-unity-attributes-readonly-d279e1e545c9 - you could probably do something similar with the EditorStyles class to add subheaders, it is custom but may not require a full editor for it - with [System.Serializable] you can make sections collapsible, which maybe could also help
ReadOnly is a common name for an Attribute that makes a serialized field non-editable in the Unity Inspector, while still being visible.
hmm maybe
and yeah ive done some editor scripting
and i really like that you can make boxes and compact things into spaces
and was hoping it was possible to do that as well without needing an whole editor script
but maybe i just make one
Yeah, sadly there isnt too much extra design functionality im aware of with GUI for the inspector, without getting into custom editor scripting - I THINK maybe you can do stuff with UIToolkit now, but I havnt looked into it in a while
ill take a look into it
Im making a noita/falling sand type game and currently each particle is a class, i want to render the map via a tile map but how do i reference a specific tile from the class?
seems expensive
what other way should i do it?
haven't actually played it but if I were to take a jab at it I'd do it like fluids
I'd expect there to be blogs about it, but ideally you'd want to render as much and fake/combine collision with larger groups
actually, sounds like something you'd attempt with the jobs system
and there's that
inparticulear here i was just currently trying to figure out a good way to (within unity) render a given array of tiles with either associated textures or simply just a color.
regarless of the underlying simulation stuff which i have been looking at things to produce, i just dont know the best way to show the resulting pixels to the screen in a efficient way
should i use a raw image or tilemap, etc...?
Not too sure about tilemap, but sprite renderer does batch pretty well for individual GOs with similar sprites and materials
the problem beyond rendering independent quads is how you're going to batch it all. Ideally you need a way to cluster them instead of always being independent verts, using graphic instancing or such as an example
I'd probably do some compute buffers and combine verts when pixels are neighboring like he does in the video
Actually, it looks like he's simulating it all on the cpu. Pretty crazy, but I'd probably attempt it via compute to cluster it.
also btw my game wont be as large as noita, ill only be readering say.... how many units can a 2d camera with a size of 40 see? at any given time
How do you guys handle code changes between unity major versions ? Do you just accept that an asset is now dead and grief for it or you try to convert it to a new version if there are even some guides for upgrading code around or you just try to finish a project in a year so this is never a problem ?
if you think it will break anything don't update, or make a copy and try that
I always have this problem when I come back to unity of assets being gone in new versions, some big features (like the free controllers we used to have in unity 4 ot 5) being gone, some new big features replacing them (have to relearn) and most of the code not compiling between major versions
ALso if you upgrade an asset it's gone forever since the new version will rewrite the old one in unity cache so once you switch to says 2022.2 the 2020.3 versio of says playmaker is gone forever. basically I'm scared of returning to unity because of that but mostly because of hacving to upgrade all my old code and old unity store assets to the 2022.2 code api...
in that case you can probably get away with spriterenderers (assuming you can't figure out the tilemap). I was even thinking just doing it all on a single texture and changing it in the fragment shader, but I'm not too sure how hard that would be to works with lol
I figured out the tile maps, (just having a single white tile and using set color on them as I can easily set a color in the constructor for each type of tile)
Plus I have no clue how writing shaders and such works currently
Seems similar to sprite rendering batching. Keep it in chunk mode and it'll do most of the dirty work for you
Hey! I need to implement google account linking to my Unity app for Android so that all the data will be transferable from one device to another. What is the way to go here? I've watched videos about Unity Cloud system and Firebase Realtime Database but which way is better in my case?
Unity has its own integration , probably safer bet
ofc there is no definite answer. depend what you need to transfer as well
Have you used it? I wonder how would player sign in. If with google account than I'll go with that, because I don't want users to create some sort of new accounts
Unity Player Account has everything in the auth for sign in including steam
Ok, thanks! I insist on google account because it's an app not a game and i need as many people to be able to link their google account
they both have google . the major difference is Unity google is the Google Play version
Is there a way to create "custom structures" ? (Like UE if anyone knows)
public struct MyCustomStruct
{
public string Data;//example
}```
Ty
C# only ? No visual asset ?
i wouldn't know how , maybe ask in #763499475641172029 DC
Ah, I think you may need ScriptableObjects in Unity
Not related to VS
oh true try SO
Im just asking if its only in c#
visual asset idk what you mean by that
I'm guessing he means a physical asset with a custom structure, that would be a ScriptableObject
just create a scriptable object that stores the data
For each point in 3d world, an icon, a text and a progress bar should be rendered.
They should be in world space.
How do you prefer to render them?
A world space canvas
Sprite + text mesh
?
The number of points can be large e.g. more than 1000. I want an efficient optimized way
If I choose canvas, I have to sort them correctly so that they can be batched. For example, first Images and then all texts
Is this a job interview task or what?
Anyone experienced in unity 2d can help me?
I am currently making 4 layers of Tiles in my game, which is ground, groundtops, groundcollidable, and ceiling, so that my characters can pass through the leaves of those trees. But I want all of the leaves of a tree to fade out when I inside those leaves. I am learning this because in the future I will have roofs, dungeons and stuff on the ceiling to create a realistic experience. I see videos on Youtube about fading a ceiling but the ceiling they design is a whole prefab not 9 blocks of tree leaves put together like mine. Is there any way I can do this? Do I need to find all adjacent leaves using a Disjoint Set to fade them out or is there an existing function in Unity which allows me to do it? Would setting up a Shader be tricky? Anyways thanks for your help.
is this a code related question?
well both code related and rendering related
i dont know where to put this question
Can someone explain why my camera follow script is causing jitters? Andf how can I fix it? https://gdl.space/tedunetiwu.cs
try putting FollowTarget() into LateUpdate()
Has anyone has this issue before ```Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/GraphicRebuildTracker.cs(24,32): error CS0117: 'CanvasRenderer' does not contain a definition for 'onRequestRebuild'
My unity ui is inside a package, I did not modify it or anything, so I don't know why I can't compile my project
This only occurs when I try to compile (Apple Silicon)
Does not occur when playing in Editor
My packages folder cannot be opened, nor I can search things in Packages
I am reinstalling Unity in hope it will fix my packages bug, it seems my packages are corrupted
can anyone help with asynchronous scene loading, i know im doing it wrong but im rly struggling to understand
been looking at tutorials but yeh
Pretty sure you are unloading the scene you just loaded after loading it 🤔
something that I usually do is request the active scene and put it in a variable before loading a new one
that way after I know it is loaded, I can just tell it to deload the variable
but you are also not waiting for the loading to be finished I think
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync("Scene2");
// Wait until the asynchronous scene fully loads
while (!asyncLoad.isDone)
{
yield return null;
}
Do i have to set the new active scene somewhere?
yielding an asyncoperation wait on its completion
ah that just works? that is nifty
i've done this but it never unloads my first active scene
You need to yield the unload operation as well
ive tried both
but i can try again
what does your code currently do Lea? Does it not look like it does anything?
Also, you never put back allowSceneActivation to true.
oh okay
Well i was told to load a transition scene then unload the current scene then load the new scene then unload transition scene
But here it never unloads the first active scene
okay yea
it does load the new scene
You should not use additive for that.
so at the top of your code where you transition save the current active scene before loading a new scene in a variable
Because, you want to have an empty scene in between
yeah i did
at the top of your routine*
Unity is kinda dumb and only clear correctly memory with an empty scene inbetween
private IEnumerator TransitionCoroutine(string nextScene)
{
var scene = SceneManager.GetActiveScene();
asyncLoad = SceneManager.LoadSceneAsync("TransitionScene", LoadSceneMode.Additive);
asyncLoad.allowSceneActivation = false;
LeftToRightAnimation();
yield return SceneManager.UnloadSceneAsync(scene);
yield return SceneManager.LoadSceneAsync(nextScene, LoadSceneMode.Additive);
RightToLeftAnimation();
yield return SceneManager.UnloadSceneAsync("TransitionScene");
}
private void LeftToRightAnimation()
{
fadeOut.gameObject.SetActive(true);
fadeOut.DOAnchorPosX(-600, 1f).SetEase(Ease.InOutSine).OnComplete(() =>
{
fadeOut.gameObject.SetActive(false);
asyncLoad.allowSceneActivation = true;
});
}
nope
this is on a dontdestroyonload maybe its because of that? i dont know never touched async haha
well my transition scene is just a blue scene basically right now
nah if it was destroyed it wouldn't work
Have you look at the console ?
And what exactly is happening ?
yeah i just get bunch of warning for having 2audio listeners
Because, it does not work can mean a lot of theings
Any error ?
nope
What is the current loaded scene when at the end
Yeah thats what i mean the first active scene never unloads
Just a blue screen scene which loads and unloads correctly
At some point, both scene are in loading, it shouldnt happen.
but isnt that the point of additive async?
Also, we do not know what you current code is
You do not want them to be loading at the same time, the loading of the next scene should only start after the transition
The latest one ?
Yeah
Is it possible that you execute the code twice ?
Im not
Then remove part of your code till you have the minimum working. Then build one step at a time
Anybody willing to give a hand of help with the unity profiler please? 😭
Been looking at a lot of tutorials and can't understand a thing from what I am looking at
For example this spike where I was just looking around. I got no idea on what to look at
Start by profiling a build and not the editor
I'll give it a shot now. Thank you!
So I'm trying to build with profiling but I'm getting tons of errors on shaders.
Don't really got any idea on what it means
@somber tapir It doesn't work
Is there any tool to convert digits 0-9 for a specific font (text mesh pro) to a sprite sheet?
I don't want to use text mesh pro component, instead I would like to have a sprite for it
Most of the time, those does not really matters. You need to look into Build completed with a result of Failed or directly in the editor log.
Can anyone else help me with this issue please
I tried putting the suggested function in LateUpdate but the player becomes jittery instead instead of the UI
is the camera parented to the player, or the player parented to the camera?
The main camera is the one that follows the player and parents the other camera
I also slightly changed the code which caused that effect https://gdl.space/woqugodira.cs
@somber tapir Also, the child camera is used by the crosshairs
What approach would you guys suggest for this? I need to rotate players when dragging. When it was one - it was fine, i just added a collider on my second camera, and calculated the drags from there. Now i need to be able to do it for multiple players.
on each platform there appears a player
i was thinking to calculate the drags from player capsule colliders, but that doesnt seem to work
okay, nevermind 😄 figured it out
did i put it in the wrong order? it should find anything more than 0 and less than 5 but i have this error instead
for(int y = 0; y < VoxelData.ChunkWidth; y++){
for(int x = 0; x < VoxelData.ChunkHeight; x++){
for(int z = 0; z < VoxelData.ChunkWidth; z++){
AddVoxelDataToChunks (new Vector3(x, y, z));
}
}
}
}
//makes sure the faces are drawn and arent drawing outside of the array //
bool CheckVoxel(Vector3 pos){
int x = Mathf.FloorToInt(pos.x);
int y = Mathf.FloorToInt(pos.y);
int z = Mathf.FloorToInt(pos.z);
if (x < 0 || x > VoxelData.ChunkWidth - 1 || y < 0 || y > VoxelData.ChunkHeight || z < 0 || z > VoxelData.ChunkWidth)
return false;
return voxelMap[x,y,z];
}
void AddVoxelDataToChunks(Vector3 pos){
for (int p = 0; p <6; p++){
if(!CheckVoxel(pos + VoxelData.faceChecks[p])){
for (int i = 0; i <6; i++){
int triangleIndex = VoxelData.voxelTris [p, i];
vertices.Add (VoxelData.voxelVerts[triangleIndex]+ pos);
triangles.Add (vertexIndex);
uvs.Add(VoxelData.voxelUvs [i]);
vertexIndex++;
}
}
}
} ```
this is my code^
where was voxelMap initialized? You need to makle sure this coordinate is within the bounds of that array
In case Gruhlum isn't here, can anyone else help me with my current camera issue above?
@somber tapir Any clues?
Sorry for asking often, I REALLY want to get rid of that jitter so I can advance
looks like your player object is moving via Rigidbody and does not have interpolation enabled.
Enable interpolation to fix it.
I will also say your camera script is weird as it seems to be moving the camera in both Update and LateUpdate. Why not just pick one?
Or better yet - why not just use Cinemachine?
why x > VoxelData.ChunkWidth - 1 and y and z not ?
The player nor its model has any rigidbody whatsoever
Also, what do you mean by that?
well you'd have to show the movement script for the player as one piece of this puzzle
I think it's pretty clear, no? You're moving the camera in both Update and LateUpdate
You still have some of the movement in Update() and some in LateUpdate(). Try putting everything in *LateUpdate().
I'd recommend LateUpdate but yeah
Here's the whole script for the ship's movement https://gdl.space/dufisiveza.cs
Now both the player and crosshairs are jittery. Does that mean I'm on the right track?
It's probably not related to your problem but I would put any movement in FixedUpdate() for your ship, otherwise the ship will move faster/slower depending on the framerate
well theoretically they're adjusting for framerate with deltaTime here transform.localPosition += new Vector3(x, y, 0) * speed * Time.deltaTime;
But it is still gonna be different. Imagine you have 1 fps vs 10 fps, after 0.5 sec with 10 fps the ship will have moved already a little while with 1 fps it is still standing still. Their velocity will be the same after 1 second, but not their positions.
If the speed is not constant, yes
However if they move in FixedUpdate they will need to do visual interpolation
it would be easier to use a Rigidbody at that point and rely on the built in interpolation
I don't like the triple cameraGO setup you have going on there. Maybe it's worth it to look into that. Do you have by chance a follow script on two of those gameObjects?
Nope, the main camera is the only one that has the script
I'm getting a little desperate trying to fix this stupid jitter with what little Unity knowledge I have
ik this is unity but does anyone know anything about batch coding ?
there is all 3, x, y,z have -1 to tell it not to look for negative blocks
not according to this
if (x < 0 || x > VoxelData.ChunkWidth - 1 || y < 0 || y > VoxelData.ChunkHeight || z < 0 || z > VoxelData.ChunkWidth)
hi! i've made my own tweening library and i'm trying to get a 2d sprite to rotate clockwise, from 0/360--> to 180, and then, continuing clockwise, to 360/0, yet i can't exactly figure out how to do it. any ideas about what i'm doing wrong?
https://paste.ofcode.org/FxkGPdCU5m5CDUPnYx3hA5
you'd have to show more code than this and also explain what's going wrong.
"SecretLerp" isn't exactly illuminating, for example
right, so what's going wrong is the tween from 180 degrees to 360 / 0.
secretlerp isn't relevant for this problem, it's just a way to lerp between 2 values while also using different kinds of easings. it's a secret
I'm trying to create a script to set a rect transforms size to the safe area, but cannot for the life of me get the scaling correct. This is what I have currently https://gdl.space/pojanuyida.cs and it's always slightly wrong (yellow is expected, red is actual)
it's definitely relevant
it seems to be exactly what the problem is based on the explanation here
anyway i wouldn't interpolate euler angles, that's a recipe for sadness
I would interpolate the quaternions
using Quaternion.Slerp
alright, i'll do that then
https://paste.ofcode.org/68DFnhuTKnDW5R7bLrG5PJ
here's the secretLerp btw
why do easingFunction(t) three times when you could do it once and reuse the result 😜
true!
i'll do that instead 😅
thanks for the help tho!
hello, i need soem guidance ofr a little part of my project. i need to make a scene where you prepare a squad of units ina a 2d plane for a rogue lite style mission (darkest dungeon prep mission screen kinda). i think this need to be new scene. but problem is how do i send the selected units data to the scene that holds the combat mechanics?
a little resume:
scene where select units -> load combat scene based on units selected previous in other scene
@leaden ice I think you are right. Looking back to the video where it all started, the camera indeed used a cinemachine
https://www.youtube.com/watch?v=JVbr7osMYTo
Support Mix and Jam on Patreon!
https://www.patreon.com/mixandjam
PROJECT REPOSITORY
https://github.com/mixandjam/StarFox-RailMovement
REFERENCES
Arwing Model
https://www.turbosquid.com/3d-models/starfox-arwing-obj-free/516643
Unity's Cinemachine Track & Dolly
https://youtu...
But I don't exactly know how it works
this kinda belongs in #💻┃code-beginner
Anyway you should do an object that holds that data and persists scene loads with DDOL
alternative can also be a scriptable Object, or combine both
hmmm interesting. can i have a scene that just holds the unit list and maybe instantiate a copy of the mi nhte combat scene?
thats also possible yes
i need the untis to be persistant, they can have levels and traits
thats what DDOL does though
it creates its own scene to put objects in that don't get destroyed until specifically told so
you would need them to be accessable through other scenes so Ideally a singleton
hmm but i cant reference this objects outside that scene right?
you absolutely can reference them
aah thx
ok, so my plan is to have a scene taht only hold the unit list and its objects, starting the combat scene it will create copies of this objects from this list i nthe battle field, after combat is solved, i will apply the changes that happened(hp damage, permanent debuffs) on the units to the referenced objects in this "list scene".
Did i understood it correctly?
sorry im a bit anxious on planning my workflows
sounds about right
Guys do you know why the Process 1 game object is centered instead of on top? Panel contains a Vertical Layout group and Processes List contains a Scroll Rect, but the object in the list stays at the center of it instead that on top (i hope to be clear)
Looking for suggestions and/or examples of a good system to use for robust dialogue scenes. These are not full cutscenes, per say. And using Timeline won't work because advancing the scene requires player input (if I was to use a timeline the character's idle animations wouldn't be able to loop while waiting for player input).
I need to be able to display dialogue, have characters move/rotate, and transition between Cinemachine cameras. All of these things I can do individually; but I'm trying to find a generic way of doing all of it, without having to hardcode every scene.
I've seen a devlog a few months ago on something like that, basically the person just created their own "programming language" to encode the actions of the dialogue into a text file
I'll see if I can find it, but it might be slightly overkill
That's basically the command pattern
pretty sure it wouldn't be too hard to incorporate waiting for user input into Timeline though
other options are things like NodeCanvas
https://hastebin.com/share/pameqowiqu.csharp
The object never moves, regardless of moveSpeed. The console constantly prints "moving".
Vector3.MoveTowards doesn't move any objects in the game
all it does it calculate a new Vector3
if you want to move an object you'll need to actually assign that new position back to some object
e.g. transform.position = Vector3.MoveTowards(...);
got it
The problem with the timeline is that you can't loop a specific section of it. You can pause it (at which point the animations would stop), but you can't break it up into sections.
But yeah a Node-like system is what would be the "norm" for what I'm looking for today. I've no experience making one though, so was seeking other avenues first (before I learn how).
Link me if you find it
I haven't been able to so far :/
im not sure if what i need is a singleton, because i can have multiple units of the same type, i think i cant just add a new unit with singletons for what i understood of the singletons description
maybe i can put the units as childd of hte singleton? not sure if that would work
the singleton isn't for the individual units
probably should read more on what a singleton can do
the thing that holds the LIST of units is the singleton
the units themselves are not.
oooooh ok
Is there any use for a gameobject without a transform component ? Is it even possible the transform component to say attach a singleton to it later or some kind of manager afterwards ? Or do I need to make sure those gameobjects are way off the camera with the transform component and not visible ?
That's not how GameObjects work.
How do I make lerp accelerate slower but still take the same amount of time
You can make an Empty GameObject.
You can use an empty gameobject. It will have no renderer
But all gos have transforms
Someone said something about the link betwene gameobjects and components yesterday (differences between them). And I realized I thought I knew what a gameobject was then I started to asks myself, ok but what if the gameobject has no components, not even a transform component. Which led to the this question
It can't
All GameObjects have a Transform
Ok that is what I thought too. Gameobject are to show things so mnimally it need to have a position in a scene
Well don't think of it that GOs are meant to "show" things. Just think of a GO as representing something in game scene space. Even if it's just a MonoBehaviour whose position/rotation/scale doesn't matter.
maybe an animation curve ?
Not necessarily show something, like a GO that holds a game manager scrupt doesnt need to visually show anything but it handles other objects.
How would I use that
That would be very helpful
Its tricky because I haven't tried this myself with a lerp, but would throw in the animationcurvle.evaluate there and have it ramp up from like 0.2 to 1 or something
This isn't the correct use case for Lerp.
You just make a animation curve on your script, then in inspector play around with the lines to get the acceleration you want. If you want it as a remapping of the T parameter that you wouldve used in the lerp then you can use the curve with values from 0 to 1. then evaluate the curve at the T you wouldve used in the lerp, and use this new value in your lerp
Take a look at this thread. There are several suggestions on achieving what you're after. https://forum.unity.com/threads/a-smooth-ease-in-out-version-of-lerp.28312/
That thread ends up suggesting what I wrote above
yup, thought of doing the same thing
I asked bots and searched but I'm not sure if I can disable GOs before a scene is initializer so their start() isn't called so you can enable them (and have their start called automatically??) after the scene start ?
You can deactivate it straight in the editor
If the prefab is disabled, it will be disabled when you instantiate it
yeah but when I reactivate them by code will their start() be called then ? I don't want their start() to be called until I decide it can be
yes it will be
why wouldn't it?
You can also use OnEnable
OnEnable is probably more appropriate.
yeah that seems to make more sense semantically and if I look at the code months later it will be more obvious. Great suggestion thanks!
Keep in mind that OnEnable is run EVERY time the object is enabled. Start is run once in the objects lifetime, the first time it is enabled
I guess at this point this is more and more and X=>Y question and I should say what problem I am trying to solve...
Im doing a fief simulation game and I need a bootstrap/managers to load assets at the start and generate the world with a lot of npcs. So There would be a generation with a manager, then the manager gets disabled another manager gets enabled and generate their part and so on. Another manager would store the list of everything that was generated for the lifetime of the game
Hello.
EventSystem.current.currentSelectedGameObject shows the currently selected GameObject.
The problem is that it doesn't show the UI Image that was clicked on. I want it to be "selected".
Is there any alternative to achieve the behavior I want or do I have to implement the full logic myself?
Can you explain exactly what you're trying to accomplish?
Image is not a Selectable component
if you want it to be selectable, attach a Selectable to it
Yes. I have a game which has a targetsSafe boolean. Basically user shouldn't be able to use some Shortcuts when any UI is being target. Like the Space shortcut shouldn't be called when user is typing something in the Input Field.
Although some shortcuts can (even have) to be used when user selects e.g. a GameObject with a tag Build Panel.
what does this have to do with selecting images?
I see. I've attached an empty Selectable with a interactable enabled. It does work now, guess it's what I need. Thank you 😄
You're right, it doesn't.
so it should be a selectable
I have to add it to every panel I want to be selected now
The description is still kinda vague but honestly I'd just not even use OnEnable or Start here, just make your own method and call it when you want it to run. It doesnt make a whole lot of sense to enable the object so code can run when you can call the code directly.
Absolutely agreed with this^
Hey guys, I have a question about just overall good coding practice.
Let's say I have a script called MapGenerator that is used strictly to generate maps, and it's independent, and I want it to stay indenpendent.
But at one step, the MapGenerator decides to spawn a chest in its maps, but the condition to spawn a special chest is if the player has a legendary sword.
What's the best practice to do this?
Should the MapGenerator have a line of code, like if (player.hasLegendaryItem()) then spawn legendaryChest();?
There are many, many ways to do it. One way is to generate with some parameters object, which might include bool includeLegendaryChest or int legendaryItemCount
then you can do e.g.
public void Generate(GenerationParams parameters) {
...
if (parameters.includeLegendaryChest) {
// spawn the chest
}
}```
My question mostly is like, if I do this line: if (player.hasLegendaryItem()) then spawn legendaryChest();?
then MapGenerator class now needs a reference to player, and it feels like it's no longer an independent sword
While the parameters thing is generic, which is good, the bool includeLegendaryChest
Hmmm, I see what u mean actually
I like it, but how do I then check if the player has the sword given that code?
that depends on the rest of your code architecture
but presumably some code will build the GenerationParams and call Generate
that code can have a reference to the player, or maybe there's an event that is triggered setting some other value when the legendary item is acquired
To make it simpler and let my architecture adapt it quick, I could just pass in a condition Action<bool>?
And if that passes, it will generate, and if not, no, and that condition could be passed in or obtained from somewhere
it would be more a Func<bool>
Oh yeah, sorry that
Yeah, that makes sense, and that other code can easily have a reference to player because it's not really part of MapGenerator
Okay thanks! I feel much better about doing it this way
Keeping my system-type scripts independent
As I said there are multiple suggestions in the thread. Some of them are actually much simpler.
Is there a way to temporarily pause a coroutine?
like, StopCoroutine, I still have a ref to it, and then StartCoroutine to start again where it left off?
a bool variable?
yield return new WaitWhile(() => isPaused);```
maybe more info helps.
My camera moves using different coroutines. Each coroutine is a unique type of following motion, but only ONE is allowed to be going off at once. I use cameraMovement = StartCoroutine(myCoroutine); for this
what I want to do now is a PauseAndPanCamera method. Where we: 1) stop the current movement, 2) start moving in a specific way via coroutine, 3) continue old movement coroutine where we left off
I think you probably want to implement a more robust actual state machine here
hmm, right now I only have a few different states, so it's hard for me to visualize the state machine until more states are added
🤔 local velocity?
I don't disagree that a state machine is a smart idea
actually, maybe I could use a simple enum
done. works. Thanks
I needed to do it manually
Vector3 Localv = transform.InverseTransformDirection(rg.velocity)
btw what happens if I have a coroutine that Stops itself in one block without yield returning?
I assume it just goes off, and takes the coroutine out of the list of IEnums that are actually running.
StopCoroutine makes no sense inside the coroutine itself
what it will do is the same that any StopCoroutine call will do
That is - the coroutine that is stopped will not continue after hitting its next yield statement
if you want to exit a coroutine from within the coroutine the correct way is yield break;
I recently noticed that my few days project became almost a 2 month project. The issue is that I didn't put good practice in making my code easy to manage. Now that I want to edit stuff it's hard. So I need to change it, however I am very scared to mess with the web of public variables that use each other. Is there a way you guys go when this happens?
Now you may see why the use of public fields is generally discouraged.
access to the internal state of a class should be judiciously controlled and only allowed by deliberately curated public methods and properties.
sounds good. I just wanted extra security to make absolutely sure exactly 1 coroutine is only ever running at a given time
Can you give a side by side example difference please?
They are basically saying that public variables that mess with each other should be private if you control the API and a public class should control access to it instead
Bad way:
public int HP;
public void TakeDamage(int damage) {
HP -= damage;
if (HP <= 0) Die();
}```
Good way:
```cs
private int _hp;
public void TakeDamage(int damage) {
_hp -= damage;
if (_hp <= 0) Die();
}```
In the first example another script can easily bypass the TakeDamage function and directly change the HP field. If they do that, we will neglect to call the Die() function, which means whatever we do in there won't happen. For example playing a death animation and sound, etc.
By making the field private we can make sure that if external code wants to change the hitpoints, they aporopriately go through the TakeDamage function which does all the right things.
or you should make an intermediary Interface class to access it so you avoid that mess if you don't control that public classes mess
that is a good example
setting public int HP is a really terrible idea
I said that because Im not sure if the other code is something they dont control like a plugin or a unity asset store asset..
Guys i have this code in my Update function, but for some reason the ray doesnt hit stuff
i have checked via a debug ray that it points in the right direction, end the thing it shjould collide with has a collider
{
Debug.Log("Boden");
leftLineRenderer.SetPosition(1, new Vector3(0, 0, lefthit.distance));
}```
Is it allowed to used visual studio 2022 instead of 2019 in unity 2022.2.15f or it will have negative side effect ? I just noticed it's 2019 so it doesnt have github copilot
Hello guys, randomly within 1-2h of playtime my game randomly freezes and crashes without any error logs. I am 90% sure that this function maybe somehow enters an infinite loop. This function is being called every minute automatically + player can also feed the character by holding a right click button which gives it xp. Anyone know what should I do?
public void AddXp(float xp)
{
if (CurrentLevel >= Constants.DEFAULT_MAX_LEVEL)
return;
CurrentXp += xp;
while (CurrentXp >= NeededXp) //neededxp is a propetry that auto calculates next xp based on the currentlevel
{
if (CurrentLevel >= Constants.DEFAULT_MAX_LEVEL)
return;
CurrentXp -= NeededXp;
CurrentLevel++;
}
}
debug it and make sure it's this loop, what can we do here with 0 context provided and other code🤷
if your game crashes, it should leave a log
like, if it actually closes, there is a log
It doesnt, it just freezes, not respoding thing and it closes
then its 90% infinite loop
You could use notepad if you wanted to (I wouldnt suggest it), but thats to say the version of VS you use shouldnt matter and you can script in any tool youd like, you just need to assign it in Edit > Preferences > External Tools: https://docs.unity3d.com/2021.1/Documentation/Manual/Preferences.html#External-Tools
I checked the event viewer on Windows
it only matters when it comes to porting games to consoles
doesnt unity need a component installed in a visual studio version to be compatible with live debugging/breakpoints in the IDE etc ?
You mean the one here: %LOCALAPPDATA%\Unity\Editor\Editor.log
Ohh that one, hold on
that's where the log will be
so if unity SaS hasnt made one for visual studio 2022 it can't be used for live debugging
it will probably say stack overflow, and point you to a specific line of code
Well you see the problem is, I've only noticed it happening in a build, not in the editor
There is a Debug.DrawRay and Debug.DrawLine, if you provide a color as the 3rd param, maybe it can help visualize what your ray is doing: https://docs.unity3d.com/ScriptReference/Debug.DrawRay.html
you also have logs from the build
in %appdata% -> local low
player.log?
%appdata% -> local low -> your company folder name -> logs in there
Player.Log would be when you are in builde
Oh really? Interesting I didnt know that, I figured for exporting a building to iOS maybe (but thats after you game is complete, before then I imagine you could use whatever you wanted to code to that point), but didnt think consoles needed a specific editor to work within Unity
Editor.Log is the log for when in Unity editor
I've also installed the Sentry plugin which like tracks crashes, errors, etc... But this is all I get from it:
Sentry.Unity.ApplicationNotResponding: Application not responding for at least 5000 ms.
Also this
when porting to some specific consoles it is required to use VS19 for example and X unity editor version available from the list so the SDK is compatible
look into the player.log. We need the stack trace
There is a VS package in the package manager which adds extra support, as long as you also have the Unity module installed in VS itself, beyond that, I dont think there should be any restrictions with debugging between Unity and any VS version, at least ive never experienced a problem with breakpoints and locals
Oh, interesting, thats a good note
thanks it seems to work vs 2022 was in the dropbox in the editor properties as well it was just set by default to vs 2019
hopefully copilot knows unity a bit 😄
That was really useful, thank you. One question is: should I declare them private or just don't declare it? It already is set private if it's not declared public.
it's a matter of personal preference. I explicitly wrote private there to illustrate the point more clearly.
Well said! Thank you!
I have a little issue with a script I’m making that pauses my game (which pauses physics simulation), pans camera, and then unpauses at target destination.
Spawning/Despawning in my game is based on my camera’s hitboxes colliding with enemies or spawnpoints.
I would like to smoothly obey this as I pan my camera, but my physics isn’t simulating while I do this.
Is there a way to try to send trigger callbacks intelligently?
pauses your game by tweaking timeScale?
pausing my game: 1) stops timescale, 2) disables many behaviours, 3) stops physics simulation
actually, I may be able to do this by manual calls.
Can I have a non-Monobehaviour listen to Unity Events?
I have just a regular C# class that I need to doing some stuff when the Unity Event fires. Basically I'm trying to inject a Monobehaviour as a dependency into my C# class and set up a listener. Can I do this? Is this a code smell?
Does seem a little odd I suppose. You need a mono anyway to hold the instance of the class, so you can listen for events and pass it onto the class to handle something.
Hmm... yeah. I might need to re-work my code. I'm not a fan of the current structure.
Basically i have a class that really doesn't need to know about Unity at all except for the current game time... which I have being updated in an update loop in a Monobehaviour that controls the game time. And that monobehaviour has an event called TimeTicked that has the current time.
I'm just having a hard time with dependencies since Monobehaviours don't allow for constructors 😦
I'm trying to learn top down 2D ai pathfinding. Does anyone have advice on this topic?
I tried to help you but the server wont let me says the algorith name and blocks it 😦
Were you going to say a*?
Because just saying "a*" without anything else would probably be too short and blocked
yeah but it got blocked 😦
oh . Not sure what I could have added to make it longer seems like a complete sentence to answer an algorithm name... anyway
Messages that are too short are filtered with regex
afaik besides voronoi which is more advanced a star is pretty much THE main 2d maps pathfinding/navigation algorithm
#🤖┃ai-navigation probably a good place to ask now too
Instead of just the name, you can make a sentence or elaborate more like "you might be looking for the A* algorithm, its a popular choice for x"
"See A*" 
is there an easy way to go find all instances of a given Component at a given time?
How can I deactivate a component that is Singletoned?
I´m trying the .enabled = false but doesn´t work
Well, it should. It being a singleton doesn't change how components work.
well im confused then
Either you're reenabling it, or confusing what enabled is supposed to do.
enabled "unchecks" the component, right?
Yes.
not really bro
Does it not "uncheck" it?
A null exception error pops up
well, that's important information
Well, that would definitely prevent it from being disabled.😅
this is the only reason you will get a null pointer exception: you wrote a.b, and a is null
Read the error, check the callstack. Look at the throwing line.
GameManager.InputManager is null .
or GameManager is a variable and it's null
but syntax highlighting suggests that it's a type
Oooooh okay
thanks a lot
stupid question, im sorry, it was so obvious
wtf
it still pops up
and none of them are null
prove that it isn't null by logging GameManager.InputManager before you try to use it
also ensure that the exception is still coming from the same line
what is exactly logging?
sorry im noob
you're already doing it :p
Debug.Log
You can pass whatever you want to it
Debug.Log(this);
ooooh ok
Need Help with save system, It's not working:
https://gdl.space/gojabegoju.cs
this pops up
okay, so GameManager.InputManager is null
but they are both active