#archived-code-general
1 messages · Page 196 of 1
I can reference it in scripts and have no issues
I'm on 2022.3.10f1 at the moment and the checkbox won't appear with no methods defined.
It also won't appear with just Awake defined.
kinda annoying having to do massive downloads to update the editor 😄
might be a 2023 thing then. i remember seeing it in the patch notes for some version
I'll have to look when I go back onto 2023.x
(i'm using an LTS release for once in my life)
I threw in an update function
still can't enable/disable it
removing and adding the script again doesn't fix either
Double click the "Script" field on that component. See what file opens.
That'll do it.
adding update to that one lets you enable/disable it
Pick the right one from the list when adding a component.
Can you give me an example of how I could contact a current script and function on the website?
(or just rename their asset)
I suppose you'd also need to rename their class afterwards.
but if both classes are in the global namespace, then one class must have a name other than Monster already
confirmed it was added in 2023
Pretty sure this is 2023-exclusive?
different namespaces
works now thanks 😄
weird thing is
I used the correct namespace when importing once
and I still couldn't drag it in
you literally just call it as if it were part of the same js script
How much worse performance is using a polygon collider with like 40 points over a box collider (2d)
If Im making a small mobile game Im guessing it doesn't really make much difference
most performance related questions can be answered with a simple "It Depends™️"
use the profiler to diagnose and check for performance issues
My friend has a project on React and he says that because of this I can't just call any script and function and get data because all the data is on React, and where he can write such a script he doesn't have access to React.
fair point...unless Im doing something wrong it appears I just can't do it anyway 😄
here is a function I use to put messages from Unity into the browser log
S4U_log : function(msg, override) {
if (override == undefined) { override = false; }
if (S4U_data.trace || override) {
console.log(msg);
}
}
putting a polygon collider on "EnemyGrimReaper" doesn't actually "fit the shape"
any idea why that doesn't work
you didn't customize its physics shape in the sprite editor
I get that the renderers are children but that should'nt matter?
actually i'm not even sure if a polygon collider will automatically work with a setup like this. i don't typically use bones to animate my sprites, i use good old fashioned sprite sheets so 🤷♂️
either way not a code question
fair point...however its also not bones
just a lot of children with sprites on it
where should I go for this kinda Q tho
but I need to get info from BackEnd from server where is info about a player name, id ...
also #🔎┃find-a-channel exists so you can find channels yourself
so you need to send messages to Unity?
yep
My code
// Send a Message to a Unity GameObject/Method
S4U_sendmessage : function(method, str) {
//_S4U_log('sendmessage to '+S4U_data.go+'.'+method+' '+str);
if (S4U_data.go != null && method != null) {
if (str == undefined) {
SendMessage(S4U_data.go, method);
}
else {
SendMessage(S4U_data.go, method, str);
}
}
},
this can be called from javascript, needs a gameobject name and a method for it it work
is it the same code?
I tried to do it but I didn't have anything in unity but there was an Object "WebManager" a function "SetInitialData"
tells me nothing
when I start the game on website, website catches an event from unity but when he use SendMessage("WebManager", "SetInitialData", JSON.stringify(unityData), nothing is called in Unity
Everything is correct, but nothing is being called, so I'm stuck at this point.
is there anything in the browser developer console?
@knotty sun There you can see "123" logs that means the event "getIntialData" came from unity and when my friend use SendMessage nothing come in unity and I don't know how to check where is an error from my side or from his side
post your jslib to a paste site
just for information, Unity don't have an option for really avoid agents bumping into each others
NullReferenceException: Object reference not set to an instance of an object
Fighter.SetStates (UnityEngine.Vector3 _currentVelocity) (at Assets/Scripts/Enemy/Base/Fighter.cs:108)
EnemyMonster.SetStates (UnityEngine.Vector3 _currentVelocity) (at Assets/Scripts/Enemy/Base/EnemyMonster.cs:36)
Fighter.JumpsandChecks (UnityEngine.Vector3 movement, System.Boolean jump, System.Boolean down, UnityEngine.Transform target) (at Assets/Scripts/Enemy/Base/Fighter.cs:92)
EnemyCharacter.MoveEnemy (UnityEngine.Vector3 velocity, System.Boolean jump, System.Boolean down) (at Assets/Scripts/Enemy/Base/EnemyCharacter.cs:82)
EnemyIdleStandStill.DoFrameUpdateLogic () (at Assets/Scripts/Enemy/Behavior Logic/Idle/EnemyIdleStandStill.cs:31)
EnemyIdleState.FrameUpdate () (at Assets/Scripts/Enemy/State Machine/ConcreteStates/EnemyIdleState.cs:32)
EnemyCharacter.Update () (at Assets/Scripts/Enemy/Base/EnemyCharacter.cs:63)
any idea which line is actually the issue?
I've tried debugging like 10 variables and having none be null so far
Fighter.SetStates (UnityEngine.Vector3 _currentVelocity) (at Assets/Scripts/Enemy/Base/Fighter.cs:108)
any idea why doubleclicking the error took me to a different location and not there?
nope
weird
Unity
I've had problems with that. It takes you one frame back in the callstack
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Rather than calling the bot again, you could have just looked at the one you called in the other channel. Just fyi
please don't report mods
Stop spamming and I might not
ok
is there a question to this code or...
The code, like all GPT code is crap
yes i said to chatgpt to fix my script ok
worse thing is, the one who posted it has no idea
no, not ok, do not post untested gpt code on this server #📖┃code-of-conduct
forgive me
private void OnCollisionEnter2D(Collision2D collision)
{
var tag = collision.transform.tag;
if (tag == "Player")
{
collidingObjects.Add(collision);
}
}
private void OnCollisionExit2D(Collision2D collision)
{
collidingObjects.Remove(collision);
}
void DealDamageToColliding()
{
foreach (var collision in collidingObjects)
{
// Check if the object is still in the list (it might have been removed in OnTriggerExit)
if (collidingObjects.Contains(collision))
{
Fighter colFighter = collision.gameObject.GetComponent<Fighter>();
if(colFighter != null)
{
colFighter.Damage(Mathf.FloorToInt(stats.attackDmg * 0.75f));
Debug.Log("damaging: " + collision.gameObject.tag);
}
else
{
Debug.Log("Couldn't find fighter, tag = " + collision.gameObject.tag);
}
}
}
}
Couldn't find fighter, tag = Wall
It shouldn't be adding any collisions to my list unless tag = player......
so how is it debugging tag=wall
I'm pretty sure the Collision2D you're passed in OnCollisionEnter2D gets reused
I would just use a collection of Collider or GameObject, not of Collision2D
it's a class, not a struct
Hello
yeah not wise to hang onto it
anyway, yeah, just store Colliders or GameObjects or something else
👍
my character can no longer "ride" the dog lol
works great 😄
wasn't taking damage prevously lol
public class CameraController : MonoBehaviour
{
public float rotateSpeed = 10.0f, speed = 10.0f, zoomSpeed = 10.0f;
private float _mult = 1f;
private void Update()
{
float hor = Input.GetAxis("Horizontal");
float ver = Input.GetAxis("Vertical");
float rotate = 0f;
if (Input.GetKey(KeyCode.Q))
rotate = -1f;
else if (Input.GetKey(KeyCode.E))
rotate = 1f;
_mult = Input.GetKey(KeyCode.LeftShift) ? 2f : 1f;
transform.Rotate(Vector3.up * rotateSpeed * Time.deltaTime * rotate * _mult, Space.World );
transform.Translate(new Vector3(hor, 0, ver) * Time.deltaTime * _mult * speed, Space.Self);
transform.position += transform.up * zoomSpeed * Time.deltaTime * Input.GetAxis("Mouse ScrollWheel");
transform.position = new Vector3(
transform.position.x);
Mathf.Clamp(transform.position.y, -20f, 30f);
transform.position.z;
}
}
Please help me, what is wrong here?
You're supposed to tell us what's wrong
And format your code please
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
this is not a useful question. plesae read through#854851968446365696 and ask again
This code is supposed to find a random point on the navmesh within a set radius, and make sure it isnt too close to the boss and make sure its a valid point not inside of an object
it worked fine before adding the Vector3.Distance if statement but now it just goes into an infinite loop and crashes my editor
the idea behind that if statement is to make sure the point isnt too close to the boss and to generate a new point if it is
where is this code? is it in a component on the boss?
i'm wondering whose transform that is
Well, consider what happens if that condition is true. It skips the break condition and checks again, but neither hit or transform have moved, so the condition is going to be true again
Meaning it's going to skip the break again
oh, duh
the boss position
you need to re-randomize the point
how could I go about doing that, cause i was wondering if continue would would make it regenerate a new hit position
it would sample the mesh again, sure
continue just means "Skip to the next iteration of this for loop"
but that's not going to give you a new random spawnPoint...
because you're right I just need a new hit position
Nothing inside the for loop changes the spawn point
not a new hit position. you need a new spawnPoint
recomputing the hit position over and over would only matter if SamplePosition behaved randomly
I was thinking you were comparing the distance to the wrong object
so just move that in there correct?
sure
i would also suggest adding a "bail out" condition
if you try 100 times, just give up and fail
Sure, but you should probably add an escape clause
Yea what they said ^
so the game won't explode if the boss falls out of the map
add in a maximum tries count
you can also relax your standards first
so, if you tried 10 times, relax the min spawn radius, and if you tried 100 times, fail
alright thats a good idea
cause the issue is that when the enemy spawns too close to the boss it causes the boss to start moving which is unintended
cause of colliders
Not quite sure how to google this so, if I do Coroutine someCoroutine = StartCoroutine(randomCoroutine()) then what happens to someCoroutine once the coroutine reached the end, is it set to null?
Objects can't really "get set to null"
that's just a clever trick unity pulls on you
a destroyed game object, for example, will equal null
it's still a non-null reference
I'm not sure if Coroutine starts equalling null after the coroutine ends
(note that this doesn't even apply to Coroutine -- only objects derived from UnityEngine.Object do that)
Can anyone recommend the most popular / widely used testing options for Unity? My team lead has asked me to do some research into our options for implementing testing.
yeah, went and checked
nothing special happens when the coroutine is over
i'd like some help trying to figure out this issue i'm having.
Working on a dungeong eneration algorithm, i have this setup where i'mm connecting two separate rooms, there's a sphere in the center of the two intersecting doors to represent the pivot point.
Is there a way i could calculate the required angle of rotation given any setup (first three images) so i can rotate the room so it connects correctly? (fourth image)
- Debug.Log( (Good for very quick spot testing)
- Unity Profiler (for optimization)
- Debug mode where visual studio connects to Unity (good to check the state of everything to see what variables are)
- Gizmos (good to visualize some things that you want to readily see)
- Debug.Assert (Anyone who doesn’t use these liberally is a novice)
Thank you, I do use most of these although I'm looking more for like a test framework that supports automated unit testing. We were implementing the Unity Test Framework and after a couple days of things not working and there being very little support for it my team lead wants me to do some research into alternatives to that.
idk about automated unit testing tbh. Most of the time, you have specific failure modes in mind to test
unless your idea is to simulate the player putting in all manner of random inputs
idk if there is a tool for that, nor do I know if that is what you have in mind
nice map !
i was watching some videos about Punch-Out!! on the Wii
it has a "soak test" mode that just plays the entire game automatically
having something like that seems like a great idea (even if you have to turn on some cheats to make it happen)
there might be tools to help simulate thrashing about randomly with a controller
ie random control stick inputs and random button inputs, and setting the relative frequency etc.
you’d probably be able to catch glitches where the player inputs buttons one frame apart which are otherwise very hard to see. Something the pokemon diamond remake definitely didn’t do lol
that too -- fuzz testing your game
I used fuzz testing to find a bunch of weird blender bugs
Use an EdgeCollider2D
my script would pick a random action and perform it until something exploded
or a polygonCollider2D in the shape of just the "hull" bit
In games cars speed up as they drive forward on max speed, and they will drive faster/speedup as long as theyre driving fast at the moment
And I coded something similar but it doesnt take few cases into account. collisions etc.
Collisions make the car slow down/stop, but the variable responsible for tracking and storing speed growth doesnt reset on collision.
And while I could try resetting acceleration on collision I think it would be better if i based the acceleration on rigidbody's velocity in the first place but i dont have any ideas.
Anyone had similar issues?
private void OnCollisionExit2D(Collision2D collision)
{
var tag = collision.gameObject.tag;
if (tag == "Platform")
{
LeavePlatform();
}
}
is there a way to make this virtual so another class can override and add to it?
private void OnCollisionExit2D(Collision2D collision)
{
collidingObjects.Remove(collision.collider);
}```
yep, just mark it as virtual
protected virtual void OnCollisionExit2D(Collision2D collision)```
and change to protected of course so child classes can access it
thanks, messed it up last time so it wasn't showing "Unity Message" and thought maybe I couldn't for some weird reason
on the child class:
protected override void OnCollisionExit2D(Collision2D collision) {
base.OnCollisionExit2D(collision); // call the parent version
// do more stuff
}```
composite colliders2D also have 2 geometry modes: outline and polygon. Outline mode gives collision only on edge. Polygon mode makes the whole thing solid.
I've no idea where the best place is to ask this, but can someone give me a heads up on the best way to test my game on my steam deck? Do I build a Linux version or Windows? How is it best to get it onto the deck? Do I need to push it to steam first or can it be side loaded? Can the steam deck be defined as a build target?
I think you can push builds to the Steam Deck directly from a Windows machine.
I use a MacBook. I used to push builds to Itch, then go to desktop mode on my Deck to update
Now I have that game on Steam (not released), and I simply push to steam + update on the deck when needed
You should make a Linux build.
The Deck can run Windows builds through Proton, but Linux should be more performant.
The Deck isn't a specific kind of platform. It's just regular Linux.
This would be more convenient, especially if you don't have the game on Steam yet, but I haven't looked into it.
I use SuperUnityBuild to automate the build process. Pushing to Itch with it is easy. Pushing to Steam was...more annoying
had to do some Shell Script Hijinks
Interesting, thank you. I'll build for Linux, that's easy, but not too sure what you mean by "push" directly from windows to the deck. Does the build process load it onto the deck via USB, or are we talking about a more manual process of getting the Linux build and loading it onto the decks FS via some mechanism (like windows file manager) outside of the unity build process?
Brilliant, thank you, that's exactly the info I was looking for!
Can somebody please help me? I'm trying to aim at a target wigh a gun, but I'm aiming with the torso. I dont know the math required to make the player aim with its gun
show vid + script
This is the current code, it works like a charm to aim at the target with the torso (this is Photon Quantum btw)
1 sec, I'll show the video
He is aiming with his torso, I need to make the some math equations to aim with the gun
I don't know how
hmm looks like some custom system
Yes, the rigging asset wasn't an option
Inverse kinematics for the arms will yield the best result, orient the gun (vertically) and the arms will follow automatically
I need to do it with math, currently
change the torso's rotation to fit the gun in the aim Target
Isn't there some way to apply an offset?
Hey! I'm looking to make a simple top-down 2D bullet that ricochets off of a collider when they touch. The bullet should use the object's rotation to decide a random direction to bounce to. It would only bounce off in a cone of about negative 60degrees to positive 60degrees. The issue I am having is that when the bullet collides with the other collider, it ricochets in a random direction from -60 to 60, but it doesn't take into account the rotation of the collider-- meaning it only travels upwards in a random direction from -60 to 60. Here is the function I am using. Where am I going wrong?
{
Debug.Log("Bullet Ricocheted!");
float randomFloat = Random.Range(-60f, 60f);
Debug.Log(randomFloat);
Vector3 ricochetDir = new(umbrella.gameObject.transform.rotation.x, umbrella.gameObject.transform.rotation.y, umbrella.gameObject.transform.rotation.z + randomFloat);
gameObject.transform.rotation = Quaternion.Euler(ricochetDir);
rb2d.velocity = shootSpeed * transform.up;
}```
The random float is the random modifier for the bullet's z direction. See how the vector3 gets the z rotation added to the randomFloat? Right now, it's almost as if it doesn't take in the current rotation of the other collider, or "umbrella", at all
umbrella.gameObject.transform.rotation.x
umbrella.gameObject.transform.rotation.z
🔥 🚒 🧯
oh no
you've made a terrible mistake here
transform.rotation is a Quaternion. It is not a set of euler angles
uh oh
you cannot read .x and .z and .y from it and expect those to be the rotations around those axes
that's not how quaternions work
Quaternion umbrellaRot = umbrella.transform.rotation;
Quaternion randomChange = Quaternion.Euler(0, 0, randomFloat);
transform.rotation = umbrellaRot * randomChange;
Try this @golden garnet
Okay, gimme a sec
* is used to basically "add" quaternions
so we're just making a random z rotation quaternion and adding it to the umbrella's rotation
Wow, you're a life saver for real
Thanks, I really appreciate it. I'll have to look into Quaternions more i guess 🫠
They're actually incredibly simple to work with. Don't make the mistake that most people make of trying to understand the math behind them. Just think of them as variables that represent a rotation. From there you just need to understand the APIs which let you create them from various parameters, and that you can combine them with * (a * b applies a first, then b), and you'll be wielding them like a master in no time.
👍 👍 👍
I am doing some level design on my grid and it's difficult to see where I am on the grid. Is there an .. object or something I can drop in my scene that has no effect in game? Like a .. manual gizmo?
is there voice channels on this discord ? if so where?
Nope
Here is the directory
https://discord.com/channels/489222168727519232/531961806646935564
Hey guys, I’m making a csr2 style game with a career mode. My current plan is have a tournamentCompleted and tournamentRacesDone variable saved to the json. Each tournament has 5 races so once tournamentRaces hits 5 I’ll have it set to 0 and tournamentCompleted++. Is this the best way of setting something like this up?
[Serializable]
public class CareerData {
public List<Tournament> tournaments;
}
[Serializable]
public class Tournament {
public string name;
public int racesDone;
public bool completed;
}```
Something like this
¯_(ツ)_/¯
im making a 3d action game and im thinking of making the enemies circle around the player before attacking but im not sure wha the best way to do it is
its gonna be a humanoid enemy so i cant really use rotate it around the player cause itd look unnatural
is there some way i might be able to use navmesh?
More something like:
[Serializable]
public class GameSave{
public int numTournamentsCompleted
public int tournamentRacesDone
}```
Then once a race is completed and the user wins increment tournamentRacesDone++ and check whether it is equal to 5. Then if 5 set to 0 and increment numTournamentsCompleted++
Sure. Just rotate it's destination around the player and feed it to the navmesh agent.
Or create a path manually.
like rotate the destination vector around the player?
Ok so what's the issue then?
Just wondering if an implementation like that would work. I have a coding background but have never used it for something such as a career mode. Just making sure before so I don’t waste time with it
ill try that thanks
There's not much here to work or not work. It's quite simple
What wouldn't work about it
Just making sure there's not any additional aspects that might prevent it from working. Or if it will cause additional unaccounted for issues vs. another method of implementation
This isn't an implementation so far it's more like just a data structure
Is there something you are worried about in particular?
like, say
player save files being messed up after you update the game?
Yea, I wanna have my code set up in the best way possible for things such as scalability. There’s not a ton of resources I’ve found on how to manage the save during a single player career mode. So I’m just shooting in the dark with that style and wanna make sure it’ll work out fine
hey there, thank you for awnser (was not at home anymore at this time) i dont understand what to do with this "Physics.queriesHItTriggers"
Documentation just say: "Static bool"
How to use this ?
You don't do anything with it. It just tells you have it enabled or not.
dont understand.
Static = not to see in inspector.
and if i enable, should this enable the Function on every singel collider, because it s a static.
Documentation is so fantastic much useless.
surly: 1 singel code example, they will die...
Static means that it's a static field.
If you enable, it would make your physics queries hit triggers by default.
It's not very detailed, because there's no reason for you to mess with it.
what i do not understand:
my onMouseEnter()
working nerly perfect in 2019.
Why not in 2022 anymore ?
This are exactly this things, hold me back to change to any update
- not compatible Assets
- lost coding
- not to understand documentations
- and things like new inputs, or such things like this
I don't think there were any relevant changes between these 2 versions.🤔
How do you inline a variable into an if statement?
So from this:
float distance = math.distance(enemyTransform[enemyIndex].Position, towers[towerIndex].Location);
if (distance < towers[towerIndex].Range)
{
//Whatever
}
to something like this?
if (ref math.distance(enemyTransform[enemyIndex].Position, towers[towerIndex].Location) < towers[towerIndex].Range)
{
//Whatever
}
On mouse enter relies on the events system and an appropriate raycaster. Perhaps when you upgrade the version, one of these breaks in your project.🤷♂️
And no clue what you mean by lost coding.😅
You don't. And shouldn't have any reason to.
Event in UI is onpointerenter this works and good ( if not, my inventory was broken, in this case i can delete the project ).
but:
this on this event ( so for 1 trigger collider ) i am lost.
There is also a solution doing this by events, but this need my biggest enemy: a void Update.
this maybe 40 Void Updates at the end no
If you want, you can inline the math.distance expression.
theres no point if u cant inline the entire thing
for Update ? in this case you want an update, waht is chacking inside the update, if your distance is close enugh ?
So replace 1 Update Function
with 2 ? 😮
... Nooooo 😄
I really don't understand what you're saying...
inline ?
Then don't do it. There's no reason to.
declare the variable inside of the conditional
if you have the secont choice with an Update, it works.
but it s a void Update.
See: i do not like void Updates, they called every frame, understand ?
me is german. and it s sometimes not easy to understand all.
Do you have a small coding example for your idea ? Can be very helpful.
No, sorry. I don't understand what you're trying to say.
But, there's no reason to be afraid of update. Games need logic executed every frame, so it's totally fine to use update.
if (float E = math.distance(X, Y) < Value)
{
transform.UniformScale = E;
}
Here's a tip: if it's difficult to express your thoughts in English, use translation tools, like google translate.
just: Some things are not simple, in this case ido.
Most i understand.
yes, but this will not solve the "Click" Problem / Enter problem. Just a distance
eh forget it, Ill just make a variable and use it twice
You could probably do it like that, but I wouldn't recommend that:
float a = 0;
if( (a = Function()) < b)
{}
The thing is that I don't understand you. Which makes it more difficult to help you.
yes, maybe.
But hm.
It will not to be good to activate a + collition to everything.
i need an other solution.
What? That was in reply to Gradient's question. Not yours.
ah , but my awnser was to "The Things that i ..."
Sorry for this missunderstanding.
No problem i wil look around
Wrong message referenced then. It's okay. Anyways, if you need proper help, you've got to make sure that the "helpers" can understand you.
hello i want to ask on how to utilize await function best
so i have an async method that return a value
this method will be called in another method
but because it's an async method it will infect the other method that use it
is there anyway to work this better?
"infect"?😅
haha if i call an await method in a normal method there will be an error of
"the 'await' operator can only be used within an async method"
so it will 'infect' the normal method to also become async method
Why would you use await in a normal method?
it's a work around of a small project test
the actual script none use await function because all data is from resource
but now i am trying to change on how they access the data to entirely online in which why i need to use await function in several method
so i try to not change the main script as much as possible
the main script only need to get a list of string which called from a return method
now i try to get this list of string online which need an await function
Wdym by "online"? And why does that require await?
Do you mean like awaiting a web request?
yup
Well, you don't need to use await. In fact, you can't as the error suggests.
If you want to block the main thread until the async method is complete, you can access the task's Result.
how to do this?
do i use the unitask waituntil's function and wait for the result not null?
I'm not sure about unitask. I was assuming you're using regular tasks.
Might want to read their docs.
hmm ok thanks
will try
Seems like they have a GetAwaiter. Could get the awaiter and call GetResults on it.
Though it seems like they warn about not using it for some reason.🤔
haha i tried several things with the await function and sometimes my editor is not responding when played
That's not possible, and even if it was it would hurt the readability of your code whilst giving nothing of benefit in return
If Unity supports it, you can fake it with pattern matching
if ("This is a string" is string myString && !string.IsNullOrEmpty(myString)) {}
But I am pretty sure that the pattern matching does not allow assignment in Unity (yet).
Other than that, this is not a question fit for this channel and you should have just Googled it.
Obviously, if you wait for the async method, it's gonna freeze the main thread until it's complete.
So i have a interface with the following code
because the GenerateGUID is always the same
but this does work in the same C# version as unity but it doesn't work here?
i mean i cant call the function like this
or this
I am making a character controller, and I have a question.
What's different between transform.Translate and transform.position in moving character?
Hello i have the following code to teleport one object to another while selected but sometimes it's just stop working, when the object teleport to a location after some time no matter how much i click on it the system doesn't see me clicking the object anymore, i tried everything, change layer, colliders, etc... but still the same issue, does someone know an alternative to this please?
here's the solution. hope this helps!
sorry I need a lotus-o-deltoid dingle-arm, not a prefamulated amulite casing. please revise your answer. thanks!
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
also, just a sanity check for preventing memory leaks
if I have an object with an event on it that has subscribers, it can still get GC'd, right?
as long as nobody can reference it
Yes - but not the other way around
the subscribers cannot be GCed
right
I have an object that represents a quicktime event. When it starts, it subscribes to events on the brains of the entities that are involved
wait, I had this backwards in my head
i was thinking the brains were subscribing to the QTE's event for some reason
ok this obviously won't clean up by itself
I'll just have the QTE object unsubscribe itself when it terminates.
i need 
Hi guys,
I'm having problem using new Unity input system.
- i have pan toool which is using left mouse button
- rotate tool which is using alt+left mouse button.
So when i do alt+leftMouseButton then it also triggers pan tool which should not happen.
there's an option for this
"Enable Input Consumption"
project settings -> input system package
it causes more specific bindings to "consume" the input, completely skipping less specific bindings
whats a good way to get an item to work similar to a spear in rain world (in 3d), where upon hitting an object it sticks to it?
on collision, make your rigidbody kinematic and parent yourself to the thing you hit
good idea
or just turn the rigidbody off entirely, possibly
er
you can't turn off a rigidbody, right
I'm thinking about potential problems when sticking to another moving object
you could always remove the component ig
an enemy might start banging into the spear
disabling your colliders would do the trick
fun
@heady iris Thanks i just enable the input consuption. now again it triggers pan tool when i release the left mouse button.
Following questions.
- I'm using InputActionReference so it doesn't continously print's out the debug of action performed. to achieve this do i have to use update and use boolean like when mouse pressed boolean becomes true and on cancelled boolean becomes false and underlying code perform?
you can call actionRef.action.IsPressed()
if my enemy.target stores the transform of say player.center
then in another code I do
Transform target = enemy.target
and then change say
target = chest.center
is the enemy.target now equal to chest.center?
95% sure it wouldn't change the enemy.target but figure I doublecheck 😄
No, that wouldn't work
I dont understand why its always shooting the farthest target and then also never switching
Its supposed to shoot closest target that it has Line of sight to
if no LOS then closest target
jumping around or moving throughout scene doesn't change that it always shoots the initial target
no where else in code does it change target
Debug.Log shows that the enemylist is indeed 2 so it also has both enemies to start
The platforms shouldn't be hit with the raycast
I've tried jumping near and above them to switch target to no success either
Hey, I try to write a test that checks whether an exception is thrown by Awake() method, but for some reason Assert does not catch any exception and test fails and anyways I get an error that exception was thrown. How can I do that properly?
On the screen there 2 Asserts I tried with
you would have to self-build cols id think
like whenever something tries to move it first checks if an object with a collider is in the tile
what error are you getting? Show the full error message
depends on what kind of "response" you're looking for
Hurray Praetor is here!
Just didnt see anyone super smart thats also helpful online and I couldnt figure out my issue myself 😦
Guessing I made some smol dumb mistake that I cant see
As in, noy being able to go through colliders
Hey guys, how does the unity Ray struct work?
Like say with pokemon
Like what is it made of
then yeah just check if the square is occupied before moving into it
As for navigation - use standard graph navigation algorithms like Djisktra's and A*
documentation?
no no
hmm
no source code ig
sick, thanks a lot
my god until now I didn't realize you could put methods in structs
I have a quiz app in unity I make the code but when I clicked any answer its always wrong can you help me
send code
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
@leaden ice So yeah, Im expecting to catch NullReferenceException, but in the end its not being caught and its thrown anyway xD
it's cut off - which line is this happening on in the test class?
have this error:
error CS0246: The type or namespace name 'Image' could not be found (are you missing a using directive or an assembly reference?)
thought this was the solution
You need to add the namespace UnityEngine.UI to the top of the of your script, this is the namespace that the type Image exists in.
but the namespace is added and error continues. any ideas?
what other namespaces are there?
you could try regen project files
show what you wrote
honestly, that should do it . . .
how do you regen
did you lose configuration (connection) with unity and your IDE?
show us script first
and its in Preferences -> External Tools
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
alr
okay, that's fine.
i'd just close and reopen my code editor first
occasionally VSCode's language server falls over and dies
is there like docs or forums where a beginner can learn about C# in unity?
a lot of the time I find myself looking at youtube tutorials
but idk if that's the best way
with c++ it certainly wasn't
well, !learn will teach you some basic concepts
🧑🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
also, checkout the pins from #💻┃code-beginner to get started . . .
https://learn.microsoft.com/en-us/dotnet/csharp/ also contains lots of information.
where
ohh your ide aint even properly setup
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
huh
follow the bot msg
i have vs code
then click and follow that link from the bot message . . .
Hello!
I'm trying to use streams from different threads but I can't find a way to make it safe.
Basically, one thread can write to the stream using a StreamWriter and the main thread must Debug.Log() what's added to the stream by the thread.
Initially, I was using this to read the new data (where consoleStream is the Stream and consoleReader a StreamReader associated with it) :
if (consoleStream.Length != oldLength){
consoleStream.Seek(oldLength, SeekOrigin.Begin);
oldLength = consoleStream.Length;
Debug.Log(consoleReader.ReadToEnd());
}
But then I figured it probably isn't thread safe if the other thread tries to write to the stream at the same time 🤔 Am I right about this? And if so, how could I make it thread safe without modifying the code to write to the stream (I don't control that code)?
To give more context, I'm executing runtime compiled C# code in a thread and I'm trying to retrieve the output (so for example if the code uses Console.WriteLine, I want to Debug.Log what was printed). For this I use Console.SetOut(), which makes Console methods write to a stream instead of a console.
If you want a thread safe stream you can use https://learn.microsoft.com/en-us/dotnet/api/system.io.stream.synchronized?view=net-7.0#system-io-stream-synchronized(system-io-stream) to get a thread safe wrapper around your stream and use that
However according to the docs here: https://learn.microsoft.com/en-us/dotnet/api/system.console?view=net-7.0
I/O operations that use these streams are synchronized, which means that multiple threads can read from, or write to, the streams.
so it might already be threadsafe
Thank you, I'll look at this !
dont know about much on c# stream, assume you havent synchronized your stream, this is not thread safe and one thread write, one thread read
if stream length increase after oldlength=stream.length, you will still enter the if statement next round but seek start from oldlength, and debug.log some words that are already printed
i think you should use concurrency queue, but you cant change your code.....
ok so... i followed the instructions, but error persists. vscode was already opening my files before.
i did the config, regen, nothing changed
Yes that's the kind of things I was worried about 😦
I´ve had this error hapen before with old assets using outdated API and I had to change some variables or add namespace
but now I can´t figure out what´s wrong
Hi! I'm trying to merge two lists of NavMeshBuildSource: one is a list and another is a list derived from a dictionary (so a list of KeyCollection of which the keys are NavMeshBuildSources). I initialize the list from the list of pair collections with this line of code: List<NavMeshBuildSource> mergedSourcesList = new List<NavMeshBuildSource>(obj.source2); where obj.source2 is a list of type public Dictionary<NavMeshBuildSource, GameObject>.KeyCollection source2;. This works perfectly well, until the list is too big and it crashes with this exception: System.ArgumentException: Destination array is not long enough to copy all the items in the collection. Check array index and length.
at System.Collections.Generic.Dictionary2+KeyCollection[TKey,TValue].CopyTo (TKey[] array, System.Int32 index) [0x0002a] in <787acc3c9a4c471ba7d971300105af24>:0 at System.Collections.Generic.List1[T]..ctor (System.Collections.Generic.IEnumerable`1[T] collection) [0x0003b] in <787acc3c9a4c471ba7d971300105af24>:0
at NavMeshCarver.MergeSourcesThread () [0x0002f] in D:[...][the place where the list is initialized as shown above.]
UnityEngine.Debug:LogWarning (object)
What can I do to avid this exception? It seems like the keyCollection is being initialized in a list that is too small to contain all of the keys. I've never encountered such error
when a navmeshsurface bakes does it bake everything in the scene or just the things that it parents
(you may recall my pathfinding issues from earlier)
It's kinda weird storing this KeyCollection on a long lived basis
hoiw about just:
mergedSourcesList = whateverDictionary.Keys.ToList();```
basically, can I have one navmeshsurface in the scene and just ocassinally rebake it
and that'll do pathing
Can't do it - it's being done inside a thread and the dictionary is constantly being modified by the main thread (and sometimes by other threads, in a safe way). What the main thread do to avoid causing problem is creating a copy of the keys and simply pushing it in a ConcurrentQueue list, taking a "screenshot" of the dictionary's keys the moment the build nav mesh method gets called
the KeyCollection is NOT a copy
which is probably the root of your problem
you should copy the keys to a collection (as per my example) in the other thread, then pass the copy over to the other thread
you need to step back further than this
that's called in the main thread
yeah
oh darn
yes objectSources.Keys is a reference
and the KeyCollection is like a view into the actual dictionary
you should just make it take a list
oh.. uhm, well is there a way to create a list with it? Without running through all the dictionary
and pass in objectSources.Keys.ToList()
because creating the list takes a lot of time
no
argh
isn't it fine if it takes time, since this is in the other thread?
no, no it's not
So, I have two lists, one has all the objects of the game and the other has another good half of the obejcts (that contain chunks and thousands of other obstacles in the procedural world). The first list is a dictionary of GameObject and NavMeshBuildSource pair. Really easy to handle because you can add and remove objects from the dictionary with their reference. The other one is a list that gets created every time a build is requested. Populating it doesn't take much time. Everything works well in a thread, and I build the navmesh manually with the async method. The problem is when the dictionary has 1) to be converted in a list and 2) merged with the other list (I'm using AddRange). I moved all the code from the main thread to another thread, that "listens" to a concurrentQueue that holds a pair of KeyCollection list and the other NavMeshSourceList to be merged with. This works well until I get that exception above, and I guess it's because the keyCollection is modified while the detatched thread was still reading the queue.
if you prefer I can use pastebin to paste the whole class, but it's a bit messy, I'm still trying to optimize and tidy things 😅
Why does the dictionary have to be converted in a list / merged with another list exactly?
Because you need a single list of sources to build
and yes siunds like a threading issue - aka modifying the dict while it's being read in the other thread
The sources list is merged from the two above in the detatched thread and used again in the main thread when it's ready
That was what I was trying to avoid, but I didn't know that the list of KeyCollection is a reference...
Hey so i have a game object i want to rotate so that its orientation is always parallel to how the camera is looking at it so if the camera is looking at it down wards the object will tilt downwards etc. how would i go about doing this
And manually creating the list in the main thread simply nullifies the effort to move the code that lags in the other thread
set its transform.forward=cam.tf.foward
Cool thanks ill give that a go
I have a slight issue that MeshColliders contactOffset doesn't seem to take affect during runtime if I change it?
MeshCollider meshCol = target.GetComponent<MeshCollider>();
meshCol.convex = true;
meshCol.isTrigger = true;
meshCol.contactOffset = 0.2f;```But the trigger distance doesn't change at all? Is there a function or anything I can call to set this?
Currently, I have a zooming function with an orthographic camera, where scrolling the mousewheel changes the camera's orthographic size. If I wanted to zoom in on the mouse, I'm not sure how I'd go about having it zoom on that specific point. I'm guessing there's some sort of math I can do to move the camera as I change the ortho size so that the mouse'd position remains stationary, but I'm not entirely sure how I'd go about determining that math.
Will that still work if my cinemachine is controlling my main camera
idk but if your camera will rotate and you can get its tf it should work
Yes. Cinemachine moves the main camera.
You could also use a Copy Rotation constraint.
All our game objects are in UI. The canvas' render mode is Screen Space - Camera. Is there any way to give "depth" to the objects? So that when the character is behind an objects it's rendered behind it. I am considering giving each object a separate canvas with another Plane Distance value but perhaps there is a better way? Changing Z position in world space coordinates sounds like a bad idea. If it's unclear, the game is 2.5D
The order in the hierarchy. Towards the bottom is "front", towards the top is the "back".
You suggest moving the character in hierarchy according to where it is?
All our game objects are in UI
😬
That's kind of the source of your troubles
Probably shouldn't do that
Yeah, using some combination of transform.SetSiblingIndex and transform.SetAsLastSibling (to bring to front) or transform.SetAsFirstSibling (bring to back).
If not, I think you can do it with layer order too.
It depends on context and how you want to change the depth of things.
Ideally, you should be using SpriteRenderer and Z position for 2D with depth.
UI is really for UI... Like menus, inventory, etc.
given a max size and min orthogonal size (max size: camera dont move, min size: the point at the center of screen), so you can have a equation: camera position= t* camera original position+(1-t)***point ** where t is (current size-min size)/(max size-min size)<- this is constant
point is ofc screen to world point (input.mouse position)
this is just a linear equation, if you want fancy movement, please modify it...
When you say "this is constant" you mean just the denominator, right? Because the numerator of that should be changing as the zooming happens, right?
yes
Okay, I'm giving it a shot
The namespace '<global namespace>' already contains a definition for 'Timer'
Duplicate script
can I have one navmeshsurface that encompanies multiple objects (not one object with children))
called global namespace?
No, Timer
global namespace is where scripts that don't specifically have a namespace defined go
hello everybody i have a probleme with websocket how can help me?
There is already one outstanding 'SendAsync' call for this WebSocket instance. ReceiveAsync and SendAsync can be called simultaneously, but at most one outstanding operation for each of them is allowed at the same time
i want to click button and a want sendmessage (active tracking)
and in updatefixe => sendmessage (my postion)
when i put a button to active (tracking camera) => i have got this message (how i can do?)
BuildNavMesh is the same as baking it correct?
should be
how would you troubleshoot this
double check UI is installed as a package
you probably set something up wrong
is it possible to add new objects to a navmesh?
Branching dialogue system in Unity?
it is not
issue found, great job, heres a raise 💸
wdym new objects
you have to rebake
yes
like if I instatiate a new object while running can I bake it into the navmesh
ye yu can bake at runtime , use navmesh surface
ok ill keep trying
did you install the package
UI package?
yea
then how is it a bug lol
i thought it´s built in
it usually is there by default
but its a package
if you remove it, bye bye scripts
ioleksdfjiewlkfj I feel like i'm on the cusp of solving this issue i've had for half a year
the CUSP
So it is a missing namespace problem
calling an issue like this a unity bug feels like calling something witchcraft
you're right - it's a missing package / assembly problem
DX checks out
if (SystemInfo.deviceType == DeviceType.Handheld)
this doesn't return mobile when using Unity's built in Simulator?
simulators are not emulators
@static matrixit does feel like witch hunt tbh
Bugs with your code vs bugs with your setup
Assembly 'Assets/PlayServicesResolver/Editor/Google.JarResolver_v1.2.59.0.dll' will not be loaded due to errors:
Assembly name 'Google.JarResolver' does not match file name 'Google.JarResolver_v1.2.59.0'
this looks like... deprecated API or something?
I can find the .dlls in the project but not the Assembly name 'Google.JarResolver' so I could rename it
The assembly name is contained in the DLL, as bytes, it's the library name
so then I should rename the file instead to match the assembly name
Hey, I was following a tutorial and I am curious why there is an if state about the velocity vector which is Vector3D and it's magnitude square should be greater than 0, before we fix the smoothing of the rotation.
if (velocity.sqrMagnitude > 0) { character.transform.rotation = Quaternion.Slerp(character.transform.rotation, Quaternion.LookRotation(velocity), character.rotationDampTime); }
So, I implemented this, and it's definitely moving, but once I scroll it centers the camera on where the mouse was, meaning if you continue to scroll without moving the mouse, you're not going to end up zooming closer to the thing you were hovering over. I'm hoping to essentially increase orthographic size and keep the point under the mouse stationary as the camera zooms
if velocity is zero you'll get an invalid rotation from Quaternion.LookRotation(velocity)
it has no way of knowing which way to look when it's not moving, so it's best to just leave the previous rotation alone
Oh I get it now, velocity magnitude is the square root of the sum of the square of x,y and z and squaring it again confirms that the sum is not zero
am I right?
sqrMagnitude is simply being used because it's slightly faster to calculate than magnitude
they both will be 0 when the velocity is 0
essentially we're just checking for the velocity being 0
I see, so in either case Magnitude or sqrMagnitude we can check weather velocity is zero or not
How would I get the world position a screen point would be at if the camera were at a different orthographic size? Just changing the ortho size and doing ScreenToWorldPoint didn't do it, the two values were the same so I guess it doesn't actually move the camera until the end of the frame
hmmm for some reason it isn't re-baking
idk why
like it bakes once on startup but then it doesn't bake again when I call it again
Ah, I think I see the problem, I'm changing the Cinemachine ortho size, but I have to use the camera to get the screen to world point. If I just manually set the camera's ortho size to match instead of waiting for cinemachine to do its thing, it works
ends up doing this
any reason why it isn't baking in the new stuff?
I should probably show code lol
void GenerateFromCenter()
{
for (int x = -2; x < 3; x++)
{
for (int z = -2; z < 3; z++)
{
bool Occupied = false;
foreach (Chunk c in Chunks)
{
if(c.coords.X == x+Center.X && c.coords.Z == z + Center.Z)
{
Occupied = true;
}
}
if (!Occupied)
{
GenerateChunk(new Coords(x + Center.X, 0, z + Center.Z));
}
}
}
BuildMesh();
//Surface.transform.position = PlayerIn.transform.position;
}
public async Task BuildMesh()
{
await Task.Run(Surface.BuildNavMesh);
Surface.UpdateNavMesh(Surface.navMeshData);
}
GenerateFromCenter is called every 1 second with invokerepeating
Isn't Task.Run going to just not work here since it makes a new thread?
ahaaaaa
what should I do instead
I thought task.run would work as it has worked before
i can't imagine this ever NOT being an infinite loop except when the length is 0
yeah while is very goofy
Shouldn't this just be if, not while?
while is not goofy
while works exactly as advertised
well if just checks once, what if it tps to another wall
it can be goofy
its a shotgun of a loop
don't miss with it
if its in update it should check every frame
Won't this code just run again later?
if will suffice
its at the start
should I put it at
bc it is a collider checker
if you really need to check something every frame, it needs to go in Update
or in a coroutine
what should I use instead of task.run then?
I just need to check if its not going to spawn an enemy in a wall
while does not wait for your game to continue and frames to pass
so make it an if
there is no reason you need while, just change to if
ok ty
I think they're just trying to find a suitable starting location for the object
public void Generate()
{
Rand = Random.Range(30, 31);
WallRand = 20;
LastChunk = ChunkForLevel[Random.Range(0, ChunkForLevel.Count)];
Center = new Coords(0, 0, 0);
for (int x = -2; x < 3; x++)
{
for (int z = -2; z < 3; z++)
{
GenerateChunk(new Coords(x, 0, z), true);
}
}
Playerstats = GameObject.Find("Player").GetComponent<PlayerStats>();
Playerstats.LevelStats = this;
HasGeneratedMap = true;
Task.Run(Surface.BuildNavMesh);
Surface.UpdateNavMesh(Surface.navMeshData);
InvokeRepeating("CheckDespawn", 1, 1);
InvokeRepeating(nameof(GenerateFromCenter), 1.1f, 1.1f);
}
this does build it correctly
so they're right in that if you only check once you might pick another bad spot
yes
I do need the rebake to be asynchronoius bcause its expensive and I cant exactly have a freeze every second
are you trying to say "pick another spot until it's free?"
because this is wrong code for that
but I was also only checking for colliders once
notice you are never picking another spot again
ya
yup
I saw that
I can't just append "async" to a function and magically have it run on the not main thread correct?
no you don't want update here then, you do want a loop, you just need to write the code properly
arent they unmutable?
okay what should I do then
it doesn't matter, `OverlapCircleAll creates a brand new array every time
ah okay
this at start?
should I set up a coroutine?
On "Runtime Network Stats" what is "RTT To Server"?
Whether I send player position as float or short it shows 1.5kB/s
pretty sure "RTT" means "Round Trip Time"
not sure why it'd be showing an amount of traffic..
can you show the entire window?
I am confused too.
Should not traffic get halved when using short too?
oh, that's two different things
RTT To Server is up top
0.00 seconds
(i presume you're running the server on the same machine)
The lower graph is plotting bandwidth usage
there is more than just the player position being sent
ahh
not if it touches any of unity's stuff
ty for the info
The first two lines are the wrong way around. And you have to put in a safety valve so that it won't get stuck if there is no available free spot
I was getting so confused lol
you could absolutely do a bunch of work on another thread as long as none of it touches unity
At that point I'd consider using the Jobs system
how
I think there will always be available space
ill try looking at jobs
Jobs provides a nice system for punting work to background threads
That's what they always say
It offers some safety guarantees
and combined with Burst, you can get native code performance
is it relatively simple?
ok but how can I do it
make it a for loop for 1000 loops for example and break when it finds a spot
There is some boilerplate to learn, but I think it's reasonably simple to to get started
also if your player wasnt moving, it wasnt sending the position at all. By default it only sends when changes happen
Here, let me show you some (old-ish) code of mine
ok
dayum
alr
thank you
ty for the info
@mellow sigil this?
I am assuming those 1.5kB are necesary to be sent?
Now you're breaking when it doesn't find a spot
oh yah
the else
my bad
i dont really know whats in those 1.5kB so 🤷♂️ maybe. You wont see it at 0 unless no one is connected
I only see them when player is moving then it goes back to 0
this is all I am sending:
_x.Value = (short)(transform.position.x * 10);
_z.Value = (short)(transform.position.z * 10);
_yRot.Value = (short)(rotation);```
well, consider the naive way to move a player
send the transform
matrix4x4 is 16 floats, so that's 64 bytes
there is a network transform class which will help you avoid doing this but yea if you wanna know more id ask the NGO discord
64 * 30 would be around 1,800
I am confused with what you mean 
i dont think they send it like that at all, and itd just be 10 floats if they did for position/rotation/scale
1920 😉
right, just ballparking
but I just realized Verve is manually sending this anyway
full HD!
no, only sending those 3 values
since player move in a 2d plane I do not need X and Z rotation and Y position, nor the scale
Introduction
but, i was moving my character without adding a NetworkTransform added to my player object since I do not need the accuracy of it
There is probably some overhead from using multiple network variables.
Hi
I have A, B, C, E, and F Vector3 positions (ABFE is a rectangle)
How can I calculate the position of the D
If I have a scene with a lot of enemies that all have their own AI...how can I speed up performance?
Async/await and/or Unity Jobs
how can I get a script in library to recognise a script in assets folder?
how would Async or await be used to improve performance?
(I guess I should look into what Jobs are lol)
the script just gives an error because it cant read from assets
hey so i have my player riding a gameobject that moves and changes rotation respective of the mouse movement however when my player gets on the whole thing breaks down and spins all over the place anyone got any ideas
you cannot because that would create a circular dependency
then what do I do?
I need the script in library to read the script I have in assets
Project the vector AC on the vector AB. https://docs.unity3d.com/ScriptReference/Vector3.Project.html
do you not understand the word 'cannot'?
then whats my alternative?
put the script into the library and read that in Assembly-CSharp
what are you trying to accomplish here?
specifically.
Depending on the necessary calculations, a batch of asynchronous operations can reduce path finding costs - depending on your implementation of the AI. Consider asking in #🤖┃ai-navigation btw
I have a script in library that creates objects and I want those objects created to have a script from assets attached to them
I will take a look, thanks
gotcha, my ai is super simple...like "walk this way" or "walk towards player" 😄
Did you profile ?
Pass a Type to the library code and use the non-generic AddComponent to attach it.
tpyeof?
no, I tried to use that once but I couldn't figure out how to make it not useless 😄
typeof(SomeType) produces a Type from a type name, yes
Then you want to understand how it works because otherwise you are going to optimize the wrong things.
then figure that out.
you're asking how to dig up a treasure chest when you have no idea where it is
typeof(ScriptName)?
you could dig thousands of holes, or you could get a metal detector
I would not say "script name". typeof(TheTypeYouWant).
But yes, that's the idea.
idk, trying to use the profiler seems like trying to use a faded ripped up map
is a script name a type?
public class FooComponent : MonoBehaviour {
}
if I had a script named AppleScript it would be typeof(AppleScript)?
this declares a type named FooComponent
It's not the name of the script asset. It's the name of the actual class.
(very recent versions of unity allow the names to differ)
That is because you do not understand it. https://blog.unity.com/engine-platform/profiling-in-unity-2021-lts-what-when-and-how
more like this is all I can find and it doesn't help me at all 😄
FooComponent fc= gameObject.AddComponent(typeof(FooComponent )) as FooComponent ;
?
this is telling you that physics is taking up 7ms of your 9ms frame
It does, it means the physics is your bottleneck
Sure, but note that the library code will not know what a FooComponent is
then what do I do?
You can start by reducing collider and rigidbody that arent usefully
how do I get library to know foocomponent?
pass it a Type. The library will not be able to do anything specific with your component.
because, again, circular dependency
gameObject.AddComponent(typeof(FooComponent ))?
unless the library and the rest of your code are in the same assembly
I mean, I've got like 1 rb on each enemy and like 3 colliders
I should stop you here and ask what you mean by "library"
its a package script
Do they push each other ?
No.
hey so i have my player riding a gameobject that moves and changes rotation respective of the mouse movement however when my player gets on the whole thing breaks down and spins all over the place anyone got any ideas
don't crosspost; you just asked in #💻┃code-beginner
I want to edit the package script to add an asset script to the gameobject it creates
its a package script
they run through each other...however it doesn't appear they push each other at all
they all look like this
I mostly just use the rb for moving, checking speed and falling
maybe I should just figure out how to write my own gravity class and get rid of rb?
If they do not need to touch each other then you disable the layer in the physics
Usually you use Kinematic Rigidbody
At least, that it is what I do most of the time.
Also, if you are able to use Cercle instead of Box it should be better
I am trying to setup Unity levelplay for ads.. do I need ironsource? how to just use Unity Ads?
looks to me like if I use Kinematic I dont get gravity anymore
Obviously. You need to apply the force yourself
why use rb at all at that point
Because of collision
Also, you would most likely use the velocity property of the RB for your movement/gravity
colliders work without rb?
No.
they work, but you won't get collision events if neither side has a rigidbody.
you may also miss collisions if you're just moving colliders around without a rigidbody
Switching off continuous collision detection may improve performance
although
"SolveContinuous" is already at 0.00ms in there
Anyway, you see how profiling is actually important. Because your issue is not your managed code and you arent losing anytime with that for no reason.
indeed
so I have enemies hitting each other disabled
would disabling everything that "can't" collide help also?
Usually try to keep the minimum. However it wont make a difference if there is nothing that was actually colliding between the layer.
Also, do you have polygone collider ?
only on weapons, might need to remove a few points
had square for everything mostly
or 2 circles for AI detection
Replace the polygone collider with other shape
how would a collider for something like this normally be
just like a 4pt square around the blade instead of 8pt polygon?
or a really big square
What it is used for ?
detecting when he hits the player with the weapon
Do you need that much precision for a collision hit ?
How can i listen to the Debug/Log output of Unity? I had a in-game console working but lost the project and forgot how i did it
thanks, for some reason I didn't remember that was a thing for 2d
Primitive colliders are much faster than polygon/mesh colliders
It's a lot easier to decide if two rectangles overlap than two arbitrarily complex (and concave!) polygons
Okay nevermind i found it
you can't have 2 of a collider on the object tho?
Hey can someone please help me. I upgraded to the latest version of Unity and I was met with this wall of errors. I have tried installing tmpro
collisions general happen between two objects with two colliders
You sure can.
and yes, you can also have several colliders
It is called compound collider https://docs.unity3d.com/Packages/com.unity.physics@1.0/manual/concepts-compounds.html
ah, meant on one object 😄
You still can
However, that would be bad practice in my opinion
swapping all the box colliders to capsule and collision Detection from continous to Discrete and now I went from like 40fps->100fps thanks 😄
was definately not expecting such a massive difference
hey so i have my player riding a gameobject that moves and changes rotation respective of the mouse movement however when my player gets on the whole thing breaks down and spins all over the place anyone got any ideas
From this vague description? No, no ideas.
maybe some kind of physics interaction is happening? It's hard to say without details
do you know the game grow up im tryna make the mechanic where u ride the growing plant
I don't know that game, no
nor would knowing that game really help me in diagnosing your game's issue
So I have quite an ironic problem lmao, basically a NullReferenceException in an if statement that checks for null.
The exception is thrown on the if statement's line. I know for certain that both "block" and "block.GetComponent<BlockHandler>()" aren't null thanks to Debug.Logging them. I know that the null thing is the "surroundings[whatIsDown]", but I'm quite baffled as to why it would throw a NullReferenceException just for accessing a null value in an array and checking if it is, indeed, null. The array is also initialized and usable so that's not it either. Any help?
private void CheckDown()
{
foreach (Transform block in transform)
{
if (block.GetComponent<BlockHandler>().surroundings[whatIsDown] == null)
{
//do stuff
}
}
}
surroundings itself could be null
I tried debug logging it too just before the if statement and it's never null
one of block, block.GetComponent<BlockHandler>() or block.GetComponent<BlockHandler>().surroundings is null
that much is a fact
use Debug.Log and find out which
(assuming you're correct about which line the error is on)
the line is indeed the one with the if
block.GetComponent<BlockHandler>().surroundings[whatIsDown] being null would not cause any error here
ok so
I'll try debug logging all of them just before the if
good plan
ok so apparently
private void CheckDown()
{
Debug.Log("DOWN");
foreach (Transform block in transform)
{
Debug.Log("1: " + block);
Debug.Log("2: " + block.GetComponent<BlockHandler>());
Debug.Log("3: " + block.GetComponent<BlockHandler>().surroundings);
if (block.GetComponent<BlockHandler>().surroundings[whatIsDown] == null)
{
//do stuff
}
}
}
the 2: is printing some empty stuff
so apparently the block handler is the problem, however here I'm iterating through all the children in this object and all of them indeed have a block handler component attached
Do this:
if (block.GetComponent<BlockHandler>() == null) {
Debug.Log($"There was no block handler on {block.name}", block);
}```
it will tell you which object it is, and also you will be able to click on the debug log line in the console and it will highlight it for you
this put right before the problematic if?
yes
OH
yeah I got it thanks
for some reason in the //do stuff section I was instantiating another object and it put it as a child of this one so it bugged
still kinda weird but at least I know what's happening
this is a code channel. but likely the templates just have not been updated for it yet
Anyone good with math 😄
Me
I want to pick a random direction and go that way (like a circle)
iirc it has something to do with trig 😄
easiest way to do it is pick a direction
Random.insideUnitCircle
It does not have to do with maths btw with vectors more specifically
With methods basically
or if you want 3 dimensional direction you can use Random.onUnitSphere
not exactly what I was wanting
why not? it gets a random direction
just normalize the result
otherwise you can do:
Vector3 direction = Quaternion.Euler(0, 0, Random.Range(0f, 360f)) * Vector3.right;```
but it's basically the same thing
if I normalize wouldn't that set both the X and Y to 1 and just go at 45 degree angle?
no
it definitely will NOT do that
normalization sets the magnitude of the vector to 1
not the individual components
private Vector3 CalcluateForce(Vector3 target)
{
float distance = Vector3.Distance(new Vector3(this.transform.position.x, handPos.position.y, this.transform.position.z), target);
float deltaVx = distance / travelTime;
Vector3 velocityX = deltaVx * pm.orientation.forward;
Vector3 velocityY = Mathf.Abs(Physics.gravity.y) * (travelTime / 2) * Vector3.up;
return velocityX + velocityY;
}
For a simple projectile simulation where I calculate the initial required velocity for an object to reach a target in designated time travelTime using projectile motion, I use this method to get the velocity, but the issue I'm having is that the object always seems to fall short? Does anyone have any suggestions as to why?
do you have drag on the projectile?
new Vector3(this.transform.position.x, handPos.position.y, this.transform.position.z) does this position actually correspond to the starting position of the thing?
yes it does I just needed to make sure that the starting height was from where it launched
Why isn't it just Vector3.Distance(transform.position, target)
if it was launched at a specific height, wouldn't it be at that height?
also I have angular drag of .05 but wasn't sure why that would matter without air resistance...?
Also I don't think Vector3 velocityY = Mathf.Abs(Physics.gravity.y) * (travelTime / 2) * Vector3.up; is going to be accurate
that's only going to work in real life
Oh
hmm yeah that could be the case
I verified the output magnitudes with an online projectile motion calculator and they seemed fine
would there be anything in terms of force mode that could affect it ?
you probably want to think more along the lines of "how many fixed timesteps is it going to take to get there horizontally"? And then calculate the speed it needs to go to spend that many fixed timesteps in the air
i mean definitely - you want to be setting the velocity directly rather than adding a force
or using ForceMode.VelocityChange and ensuring it starts at 0 velocity
Currently I use AddForce(CalculateForce(target), Forcemode.Impulse);
yeah that's only going to work if it starts at 0 and the mass is exactly 1
I'll change it to VelocityChange and see if it has any effect
why not just rb.velocity = CalculateForce(target);
and rename CalculateForce to CalculateVelocity because that's what it's really doing
Alright I'm going to try it, thanks
Hey party people. In my tileset-based pixel art game the character sometimes gets stuck on tiles. I guess this is because of rounding errors. This is usually easily fixable by using composite colliders, but I do have destructible tiles. Any idea how I can ignore small differences in colliders? I would prefer something like this to say using a circle collider for the characters legs (because it then awkwardly slides down edges which doesn't fit the boxy artstyle yada yada yada). Thanks!
also note I believe this will additionally only work if the height you're launching from is the same as the height of the target object
Yeah something about the AddForce was messing it up - changing rb.velocity directly seems to do the trick. Thanks for solving my incompetency!
known issue with tilemap colliders due to the box2D physics engine. use a round bottom collider for your player and continuous collision detection on the rigidbody if you don't want to use a composite collider for the tilemap
thanks! youre right i could also change the colliders on runtime since I detect edges with raycasts anyway 🙂
How would I get the local bounds in 2020.3, Renderer doesn't provide a localBounds property in that version and I'm not sure how to calculate it
I'm not sure if there's a prettier way to do it
you can use myRenderer.transform.InverseTransformPoint on whatever points/positions you need in local space from the bounds to get the local equivalent
but you'd just need to -- yeah, that
You could iterate over the corners and build a new Bounds out of them
note that "local bounds" isn't really a thing
because once you're rotated off the world axes, they no longer really make sense
Well yeah, I just mean more bounds without rotation, without the bounds expanding based on the objects rotation
since Bounds is intended to be axis-aligned
Unless i'm asking the wrong question?
Maybe? What are you trying to do?
The bounds expands if an object is rotated, I just want the bounds without it expanding
hmm, just converting the world bounds wouldn't give you that, then
a rotated object would give you a larger bounding box than expected, since you'd be converting those inflated bound corners into local space
for what purpose?
What are you trying to accomplish with this
but yes, what is the goal here
not "to get the bounds before rotation"
that's the Y in the XY Problem
yeah im trying to word it in a way that helps, give me a moment lol
don't try to word it
just tell us what you are doing, straight up
it's fine if this is a vague and ill-defined goal
wire frame around an object, following its rotation. I don't want the bounds to expand, i want the bounds to rotate with it
ah, so maybe like a "selection box"
yeah actually suppose thats the best thing to call it
Is this a mesh renderer, or is it skinned?
mesh renderer
I'm thinking you could just record the bounds once
ultra goofy strategy: in Awake, briefly zero out the transform and record the bounds
script to capture the bounds on creation then draw the stored one
You could even generate a mesh based off of those bounds and then attach it
You could maybe do something cute like:
Vector3 localMax;
Vector3 localMin;
void Awake() {
Quaternion originalRot = transform.rotation;
transform.rotation = Quaternion.identity;
localMax = transform.InverseTransformPoint(renderer.bounds.max);
localMin = transform.InverseTransformPoint(renderer.bounds.min);
transform.rotation = originalRot;
}```
then use localMin and localMax to draw the thing later as needed
(or store all 8 points if you want, which can be derived from the max and min)
was gonna say why are you doing it 8 times
yeah sorry that was from an earlier idea lol
Anyone know why I'm getting this warning constantly?
Saving has no effect. Your class 'UnityEditor.XR.Simulation.XREnvironmentViewManager' is missing the FilePathAttribute. Use this attribute to specify where to save your ScriptableSingleton.
Only call Save() and use this attribute if you want your state to survive between sessions of Unity.
UnityEditor.XR.Simulation.XREnvironmentViewManager:OnDisable () (at ./Library/PackageCache/com.unity.xr.arfoundation@5.0.7/Editor/Simulation/XREnvironmentViewManager.cs:169)
Try updating unity and all of your packages
it's an error in the package
if that doesn't help might just be a bug in XR
Yeah... I tried updating everything and no dice 😦
ScriptableSingleton lets you store and load data for editor utilities
the FilePathAttribute is optional and lets that data persist from run to run of the editor
so it's not really harmful, but it's a nuisance
Yeah, I realized that. It's just a really annoying warning to see lol
this is a code channel
Is it in graphic right or where?
Also anyone have any thoughts on general stability of Unity 2021 vs Unity 2022?
Maybe just #💻┃unity-talk
Okay thx
well, I haven't had a crash yet in the 2022 LTS
I usually use 2023, which was blowing up in my face semi-regularly
actually, on second thought, I did have one crash (that wasn't my fault)
(this is also a #💻┃unity-talk question)
That's good to know, thanks! And yeah, I just posted over there. My b
Almost got storing the bounds to work just the rotation stuff is wonky now. Need to go look up Matrix stuff properly..
thanks
ok nvm, ruined if objects are spawned with rotation
I am having a ~weird~ problem with UnityEngine.Random. If I rapidly exit and enter play mode, I get the same RNG every time. This is in 2022.3.10f1 on macOS.
I peeked at Random.state (using reflection) and, after the first play session, the value is the same every time.
I have Domain Reload and Scene Reload disabled, so it's possible for static state to be leaking from play session to play session.
The s0 field always contains 2077314801 after the first play session. The first session's value is random, as expected.
If I wait for a few seconds before playing again, the state is randomized properly.
Searching for Random.state, Random.InitState, or Random.seed gives no results.
after interacting with the editor for a moment and hitting play again, I get a different, but still unchanging, random state
actually, yeah, the state I get after waiting for a few seconds also isn't actually random
it's just another set of values
...is it seeding with the number of seconds since exiting play mode?
nah, that isn't it
it shouldn't be, it's only supposed to be seeded once and that seed should survive domain reloads. at least according to the docs
The number I'm getting is consistent after an editor reload
Oh get outta here
Splines package.
It calls Random.InitState with the InstanceID of an object.
lol