#archived-code-general
1 messages · Page 218 of 1
How can I make an object stop falling with OnTriggerEnter?
ok, I think I figured it out. it's like the physics system makes the collider smaller by 0.015 exactly before it does .Cast. Why 0.015? No clue
that doesn't make sense. you need to be more specific
I'm making a falling block game and I need the pieces to stop falling when they're touching.
Are you using Rigidbodies to make them fall?
How do I do that?
there's a lot to unpack here
How are you currently making them fall?
you need to first understand how you are making your blocks move
are you using an IDE? this formatting is horrible
IDE?
!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
hit ctrl k ctrl e real quick to fix those indents. To answer your question though, just use a bool to store if it hit something in OnTriggerEnter. Set it to true on there, return early from update if that bool is true.
Hello!
I have a game that has users find words and it fills them in to a larger story as you collect them. Running into incongruences when I make a WebGL build. In the build, the IndexOf method always returns -1, meaning it can't find any instances of the word in the larger story. In the editor, it can find them and my function works. I assume it has something to do with asynchronous loading within WebGL, but I'm not sure how to solve that if that is the case.
TextAsset raw;
string[] wordlist;
void Awake(){
wordlist = raw.ToString().ToLower().Split(" ");
}
void FindWord(string word){
if(wordlist.Contains(word)){
int index = wordlist.IndexOf(word);
}
}
FindWord is called from a different script in the Start function. the TextAsset is preloaded.
Whats weird is that wordlist.Cointains() returns true and IndexOf returns -1. If it exists within the list, it must have an index, no?
Thank you for reading. Any solutions are advice would be appreciated.
Did you go through the code with the debugger?
trying that now. I think i've diagnosed the problem pretty closely. Is there some alternative to IndexOf I could use?
yeah, same issue going through w debugger
Do you see the contents of the wordlist in the debugger?
Can anyone help me with something in blueprint?
Can you provide some details on specific case you have debugged?
What is the searched word?
Is it contained in the list?
What index foes it have?
There are no blueprints in unity.
this isn't unreal so i assume by "blueprint" you actually mean visual scripting, in which case #763499475641172029
thank you
Hello
I am working on a script that has parallel arrays of different data types (an in-scene gameobject reference and an int value that goes with it)
I'm kinda worried that this will make it hard to manage since I'll be changing them a lot in the inspector on many instances (easy to accidently delete from one and not the other)
I'm thinking maybe a class that just stores these values would be better? Or is there a simpler way to store them in a way that keeps them together
[Serializable] // <- if you want to be able to display them in the inspector
public struct Test
{
public GameObject Data1;
public int Data2;
}
[...]
private Test[] TestData;
Thanks
Ngl I don't really remember the difference between structs and classes
I don't think I've ever used them since learning about them 😅
Struct is a value type, class is a reference type
Difference Between Struct and Class in C#
One major difference between structs and classes is that structs are value types, while classes are reference types. This means that structs are copied by value when they are passed around, while classes are copied by reference.
The text used is Hamlet, and the searched string is the word "a", just as a test case. It works perfectly in editor. In the build, wordlist.Contains(word) returns true, but IndexOf returns -1, meaning there are no cases.
So the list contains individual characters like H, a, m, l, e, t?
No, it is a list of strings of each word in hamlet. I.e ["the","prince","of","denmark"]
In this case I don't see why that should work at all
When you search for index of a, it wouldn't find, since Hamlet is not equal to a.
Aaah
IndexOf() finds the index of the occurance in a list
Okay, so the list contains all the words from the book?
yes
And in the debugger you can see the index of the first a?
Yes. and in the editor it finds and returns it correctly. Just in the build it returns -1 for some reaosn
Are you debugging the build?
Yes
it gives me the error "startIndex cannot be a negative number" because its trying to find -1 in the list when I use it
So what index does the a have in the list when you look at it in the debugger?
No, when you look at the list in the debugger...
You said that you have found the a in the list manually in the debugger, right?
Yes
Can you take a screenshot of it?
yes give me a moment
Your above code isn't really debuggable, because the local variable is never used
your method (as previously sent), effectively does nothing
That sounds a lot like the issue is somewhere else and its coincidence 😄
Well.. can you post the BombSpell.cs / Spell.cs?
You can see the letter "a" right there.
Do you need more code? I figure the core of the issue is in the IndexOf method.
Has your code changed? Because as I said, this code does nothing #archived-code-general message
It's just one script. It is called outside but the issue is in a difference between the editor and the WebGL build
I really don't know how to solve this problem because it seems like the IndexOf method just isnt working.
void FindWord(string word){
if(wordlist.Contains(word)){
int index = wordlist.IndexOf(word);
}
}
index is a local variable, and outside of that if statement it does not exist
you should share your actual code without removing things you think may not be relevant. because chances are, something you've omitted is causing the issue
Okay. Real code coming up
This class is in its own file, yeah?
Then we need to see your BombSpell and Spell classes, only thing i can imagine is if you work with some static stuff that overrides each other
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Yeah, but please post code as described above in the future
I cannot see anything apparent directly, I also have no knowledge of fishnet which complicates it 😄
Hmm... What debugger/ide is that? VS code?🤔
which object's Awake method is not running?
Well you are using the fishnet NetworkBehaviour, so there might be more things going on
He only has LavaBomb.cs -> Awake runs perfectly
He adds TestBomb.cs -> Awake on LavaBomb.cs stops working
The browser console; presumably just logging in WebGL
It's possible to connect the debugger to a WebGL build, right?🤔
in what way exactly is it not working?
please provide actual details about what exactly is not working and how you have confirmed it is not
just saying something is "not working" is not providing actual details
Here is my actual function, with all the bits and bobs:
string final = incompletestring; // text file of underscores-- missing words that will be replaced when found
foreach (string word in wordlist)
{
string temp = rawlower; //full string with all lowercase letters
int startPoint = 0;
int i = 0;
while (temp != null && temp.Contains(word) && i<200) {
int index = temp.IndexOf(word);
int finalindex = index + startPoint; //index in complete string, starting from current iteration
string currentword = raw.Substring(finalindex, word.Length); // word with proper capitalization
bool isWord = true;
if (temp[index + word.Length] != ' ' || temp[index - 1] != ' ') //check if its contained within a word
{
isWord = false;
}
if (isWord)
{
if (".,-:;".Contains(temp[index + word.Length])) // check if word ends with punctuation
{
currentword += temp[index + word.Length]; //add any punctuation
}
wordsFound++;
final = final.Remove(finalindex, currentword.Length).Insert(finalindex, currentword); //replace underscores with word
}
temp = temp.Remove(0, index + currentword.Length); // remove all text up to that point, to find next index
startPoint += index + currentword.Length; // set starting index offset
i++; //iterator to break infinite loops (of which i have not solved)
}
}
return final;
}```
i don't see any logs in Awake.
and do you have any errors in the console? because nothing you've shown so far would prevent an Awake message from being received
and your log is conveniently on the line right after something that could potentially throw an exception
make sure you are scrolling to the top of your console and viewing the first errors that appear
Unless you actually want culture to be considered in your strings you should be using StringComparison.Ordinal, or StringComparison.OrdinalIgnoreCase.
Can't say if that's your actual issue as there is a ton going on here, but I would start by making sure culture isn't involved
thats why i simplified haha 🙃
Were you actually resting the simplified version though?
Yes, i ran that to try and simplify the problem to figure out how to fix it, and it didnt work both times. So i used the simple version to ask my question
This screenshot is not from the debugger is it?
Not my VSCode debugger because it is a WebGL build.
I'm not 100% sure, but it should be possible to connect the debugger to a WebGL build.
Nevermind. It seems like it's not possible.
well creating another type that also inherits from the same base type as another wouldn't cause any issues with the other object receiving an Awake message (unless it's due to the networking framework you are using somehow).
if the object is being instantiated disabled then its Awake will not be run. that's like the only thing that would prevent a component's Awake method from being called
Well, I'm not sure then. One thing to try is to build a desktop build and see if you can reproduce the issue in it. If you can, debug it with the debugger.
One thing that I can think of is that you're hitting some limitation with playerprefs in the WebGL build. Though, if that was the case Contains would also return false. In fact I feel like it might be returning false and you just don't confirm it thoroughly.
I really doubt there's a bug with index of. If Contains returns true, there's no way IndexOf would return -1.🤔
You may have just solved my issue. Things that were not working are now working
thats what im saying!!! totally weird bug
well, there is, and that's why my answer seems to have fixed it: culture 😉
Contains is an ordinal search in a collection
IndexOf uses CurrentCulture by default; which is why it's recommended to always specify the culture
Hoolllyy shit. Wouldve taken me years to find that. C# sucks sometimes. Thank you so much.
You have singlehandedly saved my project from dying hahahaha
serious wizard shit
strings suck, there's a lot of gotchas in every programming language
Why don't Contains and IndexOf use the same default comparison mode?🤔
String.Contains does
this is just an array check, and so it's checking using equality
Oh wait, that is String.Contains
I have no idea lolLooks like it is ordinal
No, in the minimal example they used Array.Contains I think.
This method performs an ordinal (case-sensitive and culture-insensitive) comparison. The search begins at the first character position of this string and continues through the last character position.
Huh, C# is fucky
To perform a culture-sensitive or ordinal case-insensitive comparison:
On .NET Framework: Create a custom method. The following example illustrates one such approach. It defines a String extension method that includes a StringComparison parameter and indicates whether a string contains a substring when using the specified form of string comparison.
They just didn't have culture implemented in this version of .NET for Contains at all
Seriously silly
i had a headache all day racking my brain trying to figure out what the problem was
does anyone know how to work a level changing script?
That's generic in so many ways. There is no one way to "work" something gameplay specific.
You need to show your work and issues.
Probably a lot of people.
i have a few scripts for it
it doesn't seem to work though when I add a trigger and script add on to the object
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Please stop this is the worst way you could be posting code
#854851968446365696 and also look just slightly up in this conversation. I linked the code command
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ok one moment ill use this site
all these codes for scene/level changing don't work in the unity part, it doesn't show console problems though or visual studio problems though
you haven't said if its 2D or 3D?
im not sure how to function one to start it for my character to slide across to change it
its 3d
do you have at least 1 rigidbody
Idk about anyone else but I have absolutely no clue what this sentence means
my object has no rigid body
you need at least 1 between 2 colliders, triggers/coll messages wont work
I am not sure, how to function the object that starts a level changing trigger, basically when its open I don't know what is the right format to operate it in game mode to continue to the next scene.
ok i'll add one rigit body to the 3d graphic object
graphic object?
huh? this video doesn't tell us what you did
one moment
also looks like one of the collider is prob not trigger
if camera is parented to capsule and capsule has rigidbody might wanna lock that rigidbody
or better, use Cinemachine and unparent cam
the capsule has a rigid body
the object of cube has a rigid body, a script. a box collider,
if capsule has rigidbody cube doesn't really need one
go through this link, it lists everything for why your physics messages might not be working
ok so the scripts are fine?
fine would be a stretch, there really isnt much that can be fundamentally wrong though
i removed the rigid body from the object of level changing
this is definitely a #💻┃code-beginner issue for the future. go through that link still and see why its not working. Id suggest you even just test this on basic cubes so you understand the cases for when you should receive a trigger message
from the video doesn't seem cube collider is trigger
of added to box collider... a trigger?
the collider if added a box collider with a trigger checked it disappears
Does it still have a rigidbody?
Probably falls through the ground
it has a rigid body
Why?
Set it to kinematic or remove it
to keep it maintained on the ground/mass
You don't need a rigidbody for that (keeping it on the ground part. Not sure why you care about mass)
Simply NOT having a rigidbody would keep it in one spot
if this is only a trigger why does it need to be "grounded/mass"
we don't need a step-by-step
Also make sure the collider is still a trigger.
Rigidbody on player. Non-trigger collider on player. Trigger collider on portal.
ok just the box cube is set with a trigger
under box collider
with a script of GAMEPLAYUICONTROLLER(1)
oh thats the one you think works?
you tell me
from what you've shown, GameplayUIController does literally nothing by itself. It honestly seems like you dont know what your own scripts do
ill change it to nextscene
and see if it works
these scripts i have im new to
ok?
don't just guess youor way through this
you should follow a structured course
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
im asking here for pro help
the Pro help would be to go through courses
fumbling your way through it will just be confusing
you are asking in the #archived-code-general channel, where it should be expected that you know how to solve this already. No ones gonna hold your hand in this for free, go learn c# first then start to look at unity if you want to learn properly.
this is worse than a devils act around an angel
i put in about a week or two trying to do this
Tf is that supposed to mean?
That is quite literally almost nothing, you realize people study computer science in school for 4 years as a baseline right? Just because you are determined doesnt mean u can solve issues quickly, keep learning.
You've been getting like 2/3 on one help for free for over an hour...
ill try some other time if you guys are complaining about my code level
dont bother me if you dont know how to do this
good bye
I guarantee everyone who responded to you could have it working in 15 seconds. You simply dont understand your own code, and what we are saying to you
You've been told exactly how to do it many times. You were given a step by step link for solving this. You were still helped after you refused to even try it. People have bent over backwards for you. No need to be rude and selfish. Grow up
Trust that we know how to do it, because we all have done this incredibly simple task many times....
But don't worry, as per your request, I won't "bother" you again
post to a paste site please !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I'm trying to make it so that when falling my player does its falling animation, however I'm having troubel with the animation getting stuck on the jump animation, and not switching from jump to falling. Whats weird is the jump animation does not have this problem with switching between anything else. After a while of bug testing it seems like the issue is happening due to the IEnumerator JumpCooldown()
But for the life of me, I can not figure it out, if anyone has any ideas let me know. (If needed I can also post SS of the animator tab)
https://paste.ofcode.org/vhrKNrp9SQs8qi5RQEKjxW
screenshot of Animator please
I'm so sorry, I worked on this for like 4 hours, and as soon as I figure i need to ask, I find the problem, I had for whatever reason just never switched the IsFalling to true instead of false (the default) I think I need to go to bed haha
Oof, been there.
Do you guys typically use abstract classes or interfaces?
Thinking about dependency injection within Unity.
Interfaces are preferred but don't appear in the inspector.
Abstract classes do but you obviously can't inherit off of multiple.
depends entirely on the use case. With what you said about it not appearing in inspector, if you need a monobehaviour which also implements the interface then it will.
Ya but you can't just define the variable with the interface as the type and then drag any monobehaviour that implements that interface into a slot in the inspector
if you're using DI, do you even need to do that?
This might end up being a pretty basic question but:
In the attached situation, CardZoneController is an abstract class. MonsterZoneController extends CardZoneController. ConcatNoMutate expects a List<T>, where in this case T is CardZoneController.
Where have I gone wrong here? I expected this to be legal
you can convert T to U does not mean that you can convert List<T> to List<U>
eg int can be converted to long but List<int> is not List<long>
Oooh amazing, thank you!
though they are fundamently pointer...
Does anyone else know swift
Is there a way, using Unity XR, to check if HMD Rumble is turned on?
Not whether it's capable of HMD Rumble, but whether it's turned on at all.
Also what are "channels" exactly?
In the InputDevice.SendHapticFeedback() method it expects a "channel". I have set it to 0, but I don't know what a channel is. Is that about what motors to use or is it what HMD to send it to in case there are multiple?
what would swift have to do with Unity rn
Appearently you can use unity in swift
in what sense and why would you want to do that?
its not like swift is any better than c# or anything
I want to put some of my unity games on the Apple Store and maybe add a bit of swift code for certain things
not sure that explain why its required, you can do it all without swift.
but you do you lol
we are not going to know about swift here
If I have a kinematic RB at position1, and I call MovePosition(position2), where do we get collision callbacks?
do we get collision callbacks right after physics update as though we are at position1 or at position2?
and is that different for how it would be for a dynamic RB?
On the first physics update where the collision is detected, the OnCollisionEnter function is called. During updates where contact is maintained, OnCollisionStay is called and finally, OnCollisionExit indicates that contact has been broken. Trigger colliders call the analogous OnTriggerEnter, OnTriggerStay and OnTriggerExit functions. Note that for 2D physics, there are equivalent functions with 2D appended to the name, eg, OnCollisionEnter2D. Full details of these functions and code samples can be found on the Script Reference page for the MonoBehaviour class.
With normal, non-trigger collisions, there is an additional detail that at least one of the objects involved must have a non-kinematic Rigidbody (ie, Is Kinematic must be switched off). If both objects are kinematic Rigidbodies then OnCollisionEnter, etc, will not be called. With trigger collisions, this restriction doesn’t apply and so both kinematic and non-kinematic Rigidbodies will prompt a call to OnTriggerEnter when they enter a trigger collider.
I see. so OnCollisionEnter would mean position1 was not in contact, and position2 is?
Rigidbody.MovePosition moves a Rigidbody and complies with the interpolation settings. When Rigidbody interpolation is enabled, Rigidbody.MovePosition creates a smooth transition between frames. Unity moves a Rigidbody in each FixedUpdate call.
https://docs.unity3d.com/ScriptReference/Rigidbody.MovePosition.html
What do you mean ?
You gonna have the collision whenever the collision happens
during physics update, we have MovePosition from pos1 to pos2
OnCollision give callbacks with contacts etc
are these callbacks based on what the state is supposed to be when the rb is at pos2?
I understand that, but are the callbacks based on the position after MovePosition?
Unity moves a Rigidbody in each FixedUpdate call. - Rigidbody.MovePosition moves a Rigidbody and complies with the interpolation settings.
No. Read again
At least, this is what the documentation says.
If you want to be sure, you can easily create a test.
the documentation doesn’t seem to specify
It says that the rigidbody will move base on the interpolation settings each fixed update. It also states that the collision event will be called whenever the collision is detected on the physics update
In other words, it is possible that it is neither position1 or position2
so we don’t get the callback now, we would get it next frame
if I understand, when I moveposition from pos1 to pos2, and pos2 has contact with wall, that physics update just sets us in motion to pos2. then the NEXT physics update which starts us at pos2 generates contacts for existing at pos2. Is this correct?
I mean, if you do Rigidbody.MovePosition, it is obvious that you wont get the result till the end of the physics update.
You cannot do Rigidbody.MovePosition and expect to receive a OnCollision event directly after.
i understand, but the question is if I get it at the end of the upcomping physics update, or the update after the next
The documentation would suggest that it is the end of the current frame
That can be easily tested
yeah… I feel like the documentation should probably be more specific on that
I do not really think it needs to be. You are pretty much the only one that needs that level of precision
it depends on when you call it. the position moves on the next physics update which is after FixedUpdate but before Update in the same frame
https://docs.unity3d.com/Manual/ExecutionOrder.html
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hi, I’ve just learnt about the [System.NonSerialized] tag and was wondering in what situation you would use HideInInspector over NonSerialized on a public variable. Why would you want to serialize a variable but not have it show in the inspector?
you could have some other objects changing that value at edit time like some other component or an editor script but you don't want it to be directly modifiable by the developer
or if it is dependent on other values you assign in the inspector but you don't want it to do whatever necessary calculations at runtime it can be assigned to in OnValidate
HideInInspector means something might still be serialized (it’s value is still in a file), but you just don’t see it in inspector.
NonSerializedField means it just doesn’t get saved to a file period
It’s not, just somthing I’m interested in looking at. Always wanting to try something new
when you have a public field, that usually gets serialized by default. So if you want to make public int currentHealth; you probably really don’t want that sereialized
interesting, thanks
whereas a scriptable object might have a field for you to edit: jumpHeight, and then it generates and saves the value of jumpForce based on that value. You would want to HideInInspector jumpForce
got it, thank you
how do 1 way platform effectors work? is it based on velocity, or if overlapping etc?
i assume it is “if not overlapping AND hit normal vs effector ref vector angle < arc angle, then don’t ignore. Else ignore.”
kinda outta the blue, but if you were to have a tank with the road wheels as wheel bodies can you have a piece of code auto draw track lengths between them so you have dynamic tracks and suspension?
anyone knows what is this?
what does the error mean?
everything turning black
kindly help
its giving a code errror
i thought there's a problem in code, that's why
error due to this func:
hi, I have a scriptable object that I want to activate or deactivate gameobjects, run functions and activate or deactivate audio sources, for some reason it won't let me assign gameobjects [SerializeField] private UnityEvent onLoadEvents;
assets (like ScriptableObjects) cannot refer to scene objects at edit time, you'd have to subscribe to the event at runtime
oh, thanks
So, I'm exeperimenting with 2d effectors to create pass-through platforms with a tilemap. The catch is that you can collide with it from the side. I want no side collisions, and with the default settings, it shouldn't be happening.
has anyone had difficulty with Zenject dependency injection not working
I keep trying to inject a class but to no avail
it keeps saying its null
however going into a different class and injecting the same class is ok and works
not sure but Zenject is quite old and unmaintained these days. I would prefer the use of something like https://github.com/Mathijs-Bakker/Extenject which is basically a more recently maintained fork of Zenject
lol maybe I'll switch it later on its just I use it so extensively that would take me a while to switch
I would guess it's more likely a misconfiguration in this particular case than a bug in Zenject
Extenject is Zenject, it's literally a fork of it that was more recently maintained so the way you use it should be identical
What's the most efficient way you can pick out any particular range of bits from an int?
My current solution is to do a series of shifts and byte casts, not sure if there's a better way
The most efficient? Probably what you're doing.
The simplest? Probably https://learn.microsoft.com/en-us/dotnet/api/system.bitconverter?view=net-7.0
well idk exactly what you're doing
since this gives a Span<byte> which probably means it's not allocating an array like BitConverter does
Bitwise-ANDing the number with a specifically crafted one that will extract the desired bits is also an option
also note that this requires targeting .net standard 2.1
I don't think that'd work for my case since I'm trying to unpack a jumble of data from a UInt32
I've stuffed position, uv, and lighting data into a UInt32
Side-by-side?
i'm just trying to find a way to efficiently cut out portions of that UInt32 corresponding to each piece of data
yeah
Then multiple AND operations with multiple specially crafted numbers
Can't get any more efficient than that, CPUs work with bits, these instructions are literally engraved in them
You can use your Windows calculator in programmer mode to make these numbers in binary, and convert them to integers, so the code is kept compact
I think I've got a solution in mind, stemming from what you said about AND
Just some complication with extracting a range > 8 bits
Thanks man
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Since you said these numbers are packed into 1 uint32, an easy way is just extracting them 1 by 1 and bit shifting the old values out. This way you only need to know how many bits were used for each value
if you need a chunk of X bits with Y bits to the right of it, then you could do:
range = (1 << (x+1)) - 1; // this is a block of x 1’s in a row.
then range << Y gives the result
then if you just want the block of bits from the uint, you can take that number & the other number, so it gives a result with everything else to zero.
I'm trying to figure out how that works
0011_0010_1101_0011_0101_1001 (your number)
& 0000_0000_0011_1111_1100_0000 (the magic extractor)
= 0000_0000_0001_0011_0100_0000 (the extracted number)
0000_0000_0000_0000_0100_1101 (shifted 6 bits right => the result)
The shift operation can come before the extraction using &, this changes how the extractor number looks like
is this strictly necessary? Would a struct not suffice?
You mean split each into its own field?
Like a float3 for position, float2 for uv, and so on?
Main reason why I'm going thru all this trouble is specifically so I can store each vertexes info into a single UInt32
I'm creating a voxel world, so memory can get out of hand really qucik
If I was't doing this, I would be expending around 100 bytes per vertex
This way I only allocate 4
A struct of say 2 fields of 4 bytes will be as long as a single number of 8 bytes
ok question I made a timer on my mac but when I test it on aother laptop it takes forever
Plus you can tell the struct how it is laid out in memory (with the StructLayout attribute), but it's usually not necessary as it's automatically determined
oh god ptsd from computer systems
1 = 00000000001
1 << 7 = 000100000000 (7 zeros left of the 1)
(1 << 7) - 1 = 00001111111 (7 ones at the right, because adding one will make the one carry over to the 2^8 place)
that << 4 = 00011111110000 (4 zeros to the right now because we just bitshifted it)
now if you & with this mask, anything that is not in that range of ones gets (some number & 0), which is zero.
and every number within that little block gets &1, which is just itself
understand?
i didn’t count the zeros on the left, but you get my point
For example, here's a struct that stores 4 bytes on a single uint, using the manual struct layout:
[StructLayout(LayoutKind.Explicit)]
public struct Sample
{
[FieldOffset(0)] private uint _value;
[FieldOffset(0)] public byte A;
[FieldOffset(1)] public byte B;
[FieldOffset(2)] public byte C;
[FieldOffset(3)] public byte D;
}
The 4 bytes (A, B, C, D) each have an offset (from the start of the struct in memory) that falls in the range of the uint, an number on 4 bytes.
// uint value
0000_0000_0000_0000_0000_0000_0000_0000
A | B | C | D
So you can pack your own data into a single value, and still get a fairly high-level representation of it with the individual public fields!
Oh yeah I see what you’re saying.
Unfortunately since I’m using a custom mesh layout, I can’t use custom data types. I have to use a discrete set of its or floats
Also the position along each axis is 6 bits, so it wouldn’t fit neatly into bytes even if I could use custom data types
Ooo this looks interesting as hell
Will have to look into that
why not just a struct of 4 byte fields then?
nvm answered
https://docs.unity3d.com/ScriptReference/Rendering.VertexAttributeFormat.html
And this is that discrete set
Damn that's actually so useful, too bad I can't use it
ok im confused my program definitely running differently
on my windows pc and my mac
its the same script but for some reason it works on the mac system but does not work on the windows
define "works" and "does not work"
likely you have either:
- framerate dependent code
or - code which depends on execution order of scripts
neither of which is guaranteed between platforms
like can I share my code
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ok here it is
Please share as per these guidelines
The other thing you need to do is explain what exactly is going wrong with the script
What do you expect to happen anbd what's happening instead
ok this should be better sorry
This is the same thing
don't upload a file to discord
share as per the guidelines above
Paste the link hastebin gives you when you hit Save
ok ok thank you
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
there we go
sorry guys and thanks again
alright now can you explain what's going wrong with it?
yeah of course so basically on my mac this works correctly and when holding the button 2 down for timerDuration it will countdown then fade into another scene but as soon as you are on the other scene and let go of 2 it fades back
all I did was load the scene additively to begin with and created an empty gameObject to hold this script attached to it
this behaviour works fine on my mac however it takes way longer to load on my windows comp and it does not fade back properly
Sorry for the late reply, I missed your message
Thanks for hashing it out for me, that's actually so big brain
on the windows as everything works on my mac
I tried to avoid using Time.deltaTime as to avoid issues with framerates and opted to just use the yield new WaitForSeconds approach which slightly fixed it
I'm trying to figure out why there's a separate "countdown" and "fade" coroutine
however I suspect there is something wrong with my if and else if in the Control Timer
and honestly not sure why the input handling stuff needs to be a coroutine
I wanted to abstract fade and Refade into one but i kept having issues with the alpha
and not really should I just move them into update
wont make much a diff at all
yeah may be an issue with the coroutine after all in this case
when I move to update I get this error thrown
UnityEngine.Rendering.DebugManager.UpdateActions () (at Library/PackageCache/com.unity.render-pipelines.core@7.7.1/Runtime/Debugging/DebugManager.Actions.cs:176)
UnityEngine.Rendering.DebugUpdater.Update () (at Library/PackageCache/com.unity.render-pipelines.core@7.7.1/Runtime/Debugging/DebugUpdater.cs:18)```
That doesn't seem related to your script
ill check the other parts then but it was thrown when I moved the things to update
If I script is added to a GameObject during runtime, are Awake and Start still called on that script?
@leaden ice I figured out the issue is the timer coroutine
yes. Awake and OnEnable are called immediately when the component is added (or an object is instantiated). Start is called later in the frame or the next frame
howeveer how do I make a framerate independent timer without a coroutine
Accrue deltaTime in a float variable in Update
Okay. I thought that was the case, but I just wanted to be sure.
ok then do a comparison for it having reached a specific time
Exactly. You can pass the overage to the next cycle too to make it more accurate
thank you much easier than using a coroutine
@spring creek the only problem is that its undexact so i thought I would use Mathf.Approximately
however even with Mathf.Approx it not saying it ever reached duration
Show the code. But I would do >= or <= (depending on whether you're adding or subtracting)
You want something like this
private void Update()
{
currentTime += Time.deltaTime;
if (currentTime >= thresholdTime)
{
currentTime -= thresholdTime;
//do whatever
}
}
Done on my phone haha
yeah ofc i think that better
Could probably do it with time stamps as well
how would I do that?
Instead of accumulating deltas, you'd set the next expected threshold time when threshold time is met.
If Time.time > threshold, threshold = Time.time + next and do other stuff
woot. physics engine is finally coming along
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
hi can anyone take a look at this code because I am still having issues with it running just fine on my mac however not at all on my windows pc
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
yeah im like real confused why it working
on my mac but not at all on the windows pc after build
perhaps you need to add some Debug.Log statements so that you can see what is and is not happening
yeah I have been logging the time and that it actually does go into the statements
my only supposition is the Mathf.Approximately
that may be system dependent
because to me after logging everything looked ok
what is the point of Rigidbody interpolation with a kinematic rigidbody?
isn't MovePosition supposed to figure out how to make it smooth anyway?
MovePosition only happens during the physics sim
aka not every frame
so it needs interpolation too
What exactly doesn't work?
ok so the transition fades in and out properly in the unity inspector when played on my mac and takes the right amount of time until it fades
however when ran on windows pc it takes way longer doesn't fade nearly as nicely and then on the fade out becomes stuck
id share a screenrecoridng but it too large
any help appreciated for sure idk why it doing that
One little log is not gonna help you debug the issue.
Either connect the debugger and step through the code, or place more logs. In every stage of the update and then some in the coroutines too. And log important values that determine the progression of the logic.
ok ok Ill send all the logs Ive put quite a few before but everything seemed ok
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
here are the logs I did with each case
when nothing is done it is in the rest timer case so timer should still be 0 which is correct
as long as two is pressed it's in the press-down case
when it reaches about 5 seconds the fade time it goes into the fade case
then once two is pressed down it goes into the refade case
this is all correct behaviour but for some reason it doesn't on the pc
That's fine, but what about the coroutines?
I put one inside each of the coroutines tracking the elapsed time and see that it does count up to the fade duration which is 1 second
So on the PC "within refade case" is not getting printed?
yeah on the PC it does not even fade out
like this is the output on the console
when I run the log statements showing that elpasedTime of each fade is going to 1
like im only running the built version on the pc
So this logs are not from PC?
Are any logs that you've seen or shared from PC?
then it doesn't work on the pc
nope there are no logs from the pc I wouldn't know how to get live logs while the build is running
So basically the whole conversation so far was pointless
😦
What's the point in the logs from where it does work..?
open the !logs file
hmm, so if I’m doing it with a manual simulation mode, do I just move the transform, or do I just need to teleport the rigidbody to each point along the path? I’m just not sure how the physics system moves it
ok thank you sorry and ill do that rn
i guess I’m not sure what goes into motion via interpolation, because I assumed the rb was just moving along on its path each real frame
maybe I can simplify my question; on a given Update() call, assume I can work out the position this rb is supposed to be at. Do I just… set rb.position?
rigidbodies only move on the physics update. interpolation just predicts where the transform should be and updates its position each frame. but then the physics update happens and the transforms will by synced to the rigidbody's actual position
you call MovePosition and then when you call Simulate it will move there
but interpolation doesn't really work with manual Simulate calls AFAIK in any case
auto interpolation does not work, so I’m trying to figure out manual interpolation
so… during update, i should move the transform and only the transform?
And before manual similation on fixed update, I make sure the transform is on the current RB position?
at this point, i feel like the main lesson i’ve learned is to never move a transform when I have a rigidbody lol. hence why I’m looking for confirmation before a long quest of checking for bugs
I'm not sure it would be that simple. Moving the transform, might sync to the rb, so it would get moved as well eventually. Which would break things.
Unity probably moves it in some way that does not affect the rb behind the scenes.
yeah, this building a physics "engine" on top of another physics engine is going to cause some weird issues like that. since you cannot control the internal state of the rigidbody you can't really do interpolation like the rb would
I don't know if disabling Phywics.autoSyncTranaforms might help with this. Anyways, trying to interfere with how the physics engine works like that is not a great idea imho.
From the description it sounds like it might. But it's not clear wether it's enabled or disabled by default.
ok ngl Im having trouble locating %LOCALAPPDATA%\Unity\Editor\Editor.log on my windows pc i went into the folder where the build is stored and enabled hidden files and only saw Graffiti+_Data which i went into but cant find that file
you should be looking for the player log not the editor log. but you can literally just copy paste that into the address bar to open that log file
lol ok ill do thar
ye i copied and pasted
nothing yet
like it says no resultds
you paste it into the address bar of your file explorer. but that's still the wrong log file
and the one you should be looking for will have a path dependent on your project name and company name
There are other ways to do it too:
- connect your ide to the game (even possible remotely)
- connect the editor to the game(should be possible remotely as well)
do you have the editor installed on your windows computer? if not, then of course there will be no editor log.
you need to open the player log though, not the editor log.
ok yeah i dont have unity editor on my laptop
and i went searching for player log directory but couldnt find one
where did you look?
_EXECNAME_Data_\output_log.txt
i got this actually
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
that is for unity 5. are you using unity 5?
using unity 2019.4
then click the link the bot gives for the !logs documenation
I see it now
thanks @somber nacelle
ill give it a shot
yeah I just see a whole bunch of .dll files
and found the app data
but cant find localLow
copy and paste this into the address bar: %userprofile%/AppData/LocalLow
sounds like you're putting it in the search bar not the address bar
ok i tried the address bar nothing
i put the exact thing in
i found this so far user\Desktop\App\Data
but in data no localLow to be found
i searched all subdirectories as well
yeah you're obviously not going to find it if you search in the wrong location
screenshot what you see when you copy/paste %userprofile%/AppData/LocalLow into the address bar of your file explorer
yeah ofc
ok my dumbass
i found it but there are two folders with the company name
idk ill check both
how many projects you made?
it depends on what you've set in the Player Settings in your project settings
if you did not manually set it then it would be DefaultCompany
yeah bruh idk what they set it to this thing been made over 10 years its been reewritten at least idk how many times
ill check what the recent dude put fir it
is this not for your own game?
surely you have access to the project settings if you are actually legitimately working on this
yeah i do have access to it
then just look . . .
yeah
ok i found it
got into the logs
thanks again guys for the help really appreciate it
Might be useful to learn to connect the debugger next.
yeah I have it connected on my mac
but i want to do the remote to the pc
that would help a lot
If they're on the same local network, you just need to "attach to process", change connection type to remote and type in the IP of the PC. Then just select the process and connect.
Assuming you're using visual studio
yeah im on visual studio
i'm baking a nav mesh path at the start of the game for my randomly generated dungeon game but for some reason it gives out errors for different meshes in the rooms like lockers. lights, etc.
how can i fix?>
you'd need a reference to the specific instance of this class you want to use the event from
note that each instance of the class has its own event.
The error tells you.
ohhh ok thank you
I don't think what you're doing makes much sense especially if this is a MonoBehaviour
you might be able to get away with it on a ScriptableObject
You'd have to get a reference to the object which likely means Resources.Load or via Addressables
"Read/Write" must be enabled in import settings
is the code running? Use Debug.Log to check
If the code is running then the event is firing (assuming you put a log in the correct place)
want to point out that while it may have fixed it, the conclusion you drawn may be incorrect
you need to look at specifics of what exactly was null, because if it were true that events in start were failing it would affect everything else in the engine
Start is not the first frame though. It would happen as early as after all Awakes of objects that exist before the scene starts have run
or at any point during runtime
Tried to fix it and I made it more confusing haha
How do I read a JSON with a hyphen?
This didn't work for me: https://stackoverflow.com/questions/62907263/how-do-you-use-jsonutility-to-read-an-object-with-hypens-in-the-keys
(Using the JsonProperty attribute)
are you actually deserializing with newtonsoft json? because that should work just fine if you are
Ah, I guess I can't use JsonUtility with it... I'll try again, thanks
I'm curious what happens if you try to deserialize it as is? What error does it throw?
correct. you could use the "method without external dependencies" answer if you want to continue using jsonutility
Careful with Newtonsoft, use the asset store version, if you just use the dll from their github il2cpp builds break
afaik it shouldn't throw any exceptions, it would just not deserialize that property since it doesn't match the c# structure
I'm just doing it wrong - I got it from the package manager so it should be [edit] okay
I'll take a look again tomorrow, this was a frustration ask, thanks all
the package manager version is the right one to use with unity
sounds good, thanks boxfriend
is there a unity registry one now?
Hmm... Kinda weird that it wouldn't give any errors or warnings 🤔
has been for a while. i think it might even be included by default in the most recent versions but i just closed unity a few mins ago and i don't want to open it again to check lol
https://img.sidia.net/ZEyI5/HeGiNiQE96.png/raw i cant even find it
json, newtonsoft, gives nothing 😄
it's not going to show up
yo is there a way to get all prefab variants of a prefab? I'm tryna spawn in a randomly selected prefab based on a gameObject
what version of unity are you on?
Ahh alright, thats why I asked if they now have it in the registry
but it should be there by default iirc yeah
2022.3.11f1
yeah should be installed by default
it's installed by default in 2023 which is the version i'm using. and i'm fairly sure i read it should be there by default in 2022
havent removed any, just added
You have "in project" selected.
Yes, we are talking about newtonsoft json being installed by default
JsonUtility is default, you have to search for newtonsoft in the pacakge: com.unity.nuget.newtonsoft-json@3.0
which would make it be "in project"
Ah ok.
com.unity.nuget.newtonsoft-json@3.2 just add to manifest
Any big apparent challenges when switching from 2022 to 2023? Thought about switching but wasnt sure yet
not really, most of the more obvious stuff that was changed in 2023 was already marked as obsolete in 2022 or had warnings.
it's finally got some nice async features though which is the primary reason i'm using it for my current project
always project dependent
also i just found out that newtonsoft was probably installed as a dependency for one of the unity packages i installed so it may not even be a default package 🤷♂️
the bigger the project the more the likelyhood of finding edge cases and bugs in new versions
Yeah, thats for sure, was more fishing for stuff like "yeah all your URP stuff will break"-level of challenges 😄
🎲
Oh alright, that explains it
i swear i read somewhere that it should be installed by default in 2022+ though, but it's been so long that i cannot remember where i had seen that 🤷♂️
I am currently working on an FPS controller that uses a list of Vector2's to offset a raycast's direction to give the weapons predictable recoil patterns like in counter strike, How would I add an offset to a transform.forward vector that works consistently?
My vector2 contains the X Offset and Y Offset, that would change the vector3 directions X and Y
What is the Vector2 supposed to represent?
rotation angles?
transform the offset point into world space, then your shooting vector would be B - A
or just transform the vector itself
so if point is (0.5, 0.25, 0f) + (0,0,1) the result after transformation should be a point next to your forward vector
this one seems like a stretch but I figured I'd ask... Is there a way to get a refrence to an asset that you right clicked and created a new asset with. In my case my attack system requires a SO and AOC for each attack animation. While it allows me to make some cool combos and things it sucks to make new attacks. Would there be a way for me to make a system where I could right click on an animation clip, select an item like "create attack" and automatically have the SO and AOC made for me? So back to the question is there a way to get a reference to an object that was 'right clicked' and a create asset menu item was selected?
yes
[MenuItem("Assets/My Method")]
for context menu
in the method
foreach (var item in Selection.objects)
{
...
}
would you advise that I do that in the SO to be created or keep it in a seperate script?
whatever is more convenient, this is editor code so either keep it in any Editor folder or guard with #if UNITY_EDITOR #endif
best would be Editor/Utilities/CreateAttackFromAnimClip.cs
Anyone know how I can reset the prefab editing scene via code?
what do you mean by reset?
you can access its api https://docs.unity3d.com/2020.1/Documentation/ScriptReference/SceneManagement.Stage.html
I'll have a look, thanks
I've been using that but I don't see how I reset the prefab using it
Okay that's the issue I have I guess, I try to open it when it's already open and it just causes my code to spam new assets in it. How do I close it?
Thank you
Just wanna say that i did end up fixing this, used a bit of an interesting work around, but the results are great
To minimize confusion, you may want to update your other post and mark as "solved" if you now have it worked out
Hello. I am making an online game, but the problem I encountered is that the reloading domain is repeated endlessly and never ends.
hey guys i am developing a game but when i share a build of it to my friends, their computers detect it as a virus. i'm not too sure if it happens with any other games but its quite weird. any way to fix?
should just be an option for your friends to ignore their computers best intentions and allow themselves to run it anyways. Any exe can be dangerous to a computer, which is why it checks. You'll need to go through a platform (like steam) if you want this not to happen for your finished product
ah alr, ty 🙂
Quick architecture question. Got a system where when the player clicks, if they click on an interactable object, it interacts with the object with an interface. If it's not interactable, and the player has something in their hand, it uses that item instead, with interfaces again. Is there any way to do this without having the player aiming/click manager be dependent on the interaction systems? I'd like to preserve event based architecture as long as I can.
How is it dependent now?
The click manager isn't dependent right now, it's just running an event to the interaction systems
I'd like to keep that if possible, but I don't (ideally) want a dependency on the player item use system to the player interaction system
Could write some kind of event consumer system.
Yeah that's what I was thinking, event that passes from system to system and if a system can use it, it eats the event and stops passing it on.
The game/input manager would dispatch the events to all subscribers as long as they don't consume the event.
So, true/false response from each system about if the system used it?
Sounds good.
Good Morning!
Im doing an multiplayer game with Server, Host and Client Mode (Like Ark or Conan).
i Found some problem with scene management, i start an server in one computer, and trying to conect from another
conection works perfectly but scene managemente needs change logic...
when i connect server and client change scene to same...
i need each client play in our scene but one client can travel to other player scene too
i dont know how to do it ... anyone can help me with some logic, maybe ?
Yeah. The problem is ordering. When a system subscribes it needs to pass it's priority or something, but the what if 2 systems have the same priority?
Shouldn't happen ever for this implementation, if it does I've got fucking no ideas.
Priority system and event consumer will work, tysm
Wdym? Do you want each player to have their own instance of the world/scene?
Hey
I've been coding a game
But I need some help figuring out how to store variables in a neat way
Across sprites
Because all the ways I've been using
Are quite clunky
I'm assuming you meant the post on Brackets discord?
If so, I just added the solved tag and added an explanation of what I did incase someone finds that useful in the future 👍
any way to change layer of all gameobjects in gameobject's tree (children) other than go.layer=xxx in a loop?
i think no, you need to use recursive way (or get all the transforms)
its not correctly? cuz, one player can go to planet 1 while other player can stay on planet 2,each planet is an scene
You can only have 1 scene active (You can have additive, but they will interfere one with an other) at a time in a server. You either prevent player from going to a new scene alone or you have two server. You could also make things such as you can load all scene additively. This way the server could have multiple scene open. However, you gotta be careful about the fact that each scene could overlap.
Hi, any ideas on how to avoid enums that are used across multiple classes to do some logic based on the enum value?
Imagine scenario:
- you have a
Weapon.csscript that containsWeaponType enum - using Raycast you hit
IDamageableobject, let's sayEnemy.cs - you call
OnHitmethod inside theWeapon.cson that IDamageable object - the
OnHitmethod insideEnemy.cshas input parameterWeaponTypeand based on what value from this enum is there it spawns decal (Pistol = Standard Decal; Rocket launcher = Huge Decal).
I'm looking for any feedback, advice, etc.
Even though this works fine it always feels a bit clunky when adding new value to the enum and then trying to find out each class that uses such enum to provide new logic there.
Thanks.
Maybe Weapon.cs should just have a [SerializeField] Texture decal; and then pass it in as aparameter when you call OnHit()
or maybe wrap up all the info you need as like:
public struct HitDetails {
public float damage;
public Texture decal;
public float knockbackForce;
}``` and pass _that_ in as a parameter
That would work if you knew what are you hitting, but the Weapon doesn't know that. Hence the interface IDamagable.Onhit()
why does it matter what you're hitting?
Wall vs human flesh = different decal.
I thought it was the weapon that decided the decal
Well, the weapon tells whether it is a pistol or explosive (rocket launcher, grenade).
If pistol - wall makes just small hole, flesh small red hole.
If explosive - wall makes burnt black area, flesh also burnt black area.
Sounds like an enum would be appriopriate then, as part of say a struct like this
and the thing being hit can have a mapping of weapon type or damage type to the decals it needs
you can use a Dictionary instead of a switch if you want
sounds like a good idea
I'd make the decal into a separate script that you can then pass via parameter
could you tell me more about the dicitonary?
I assume some static Dictionary <WeaponType, Decal Texture>?
humm, how things need work on multiplayer servers like ARK or Conan?
Server have multiple aditive scenes?
It must be a single scene
I do not think there is any loading screen
hummm bad Game examples hahaha , maybe like Empyrion Galact Survival who you can fly over many planets
No idea, never played this games. (Is there any loading screen ?) You could have something like: if two players are in the same scene, connect them (In a Peer to Peer connection). Otherwise, do not.
As I build my physics engine, I’m getting to refactoring code that allows some entities to stay grounded (so they can move along slopes).
Previously with dynamicRBs: At start of FixedUpdate, do a logic check to see if we should try to snap to a floor. If true, ground check down, and if we hit, force us down and keep knowledge of slope normal. Then when evaluating horizontal movement, add force calculated to be along the slope.
I’m wondering if there is a smarter way to do this now that I have a semi-working pseudo physics engine. To try to keep grounded movement along a slope.
Having work on a Survival Multiplayer games with dedicated server, we used a single scene for everything. That being said, it was more inline with ARK/Conan
Are there any suggestions for maintaining ground connection along slopes?
Single Scene ?
hummm maybe i thinking wrong... my game will generate planets procedurally (will be many)... Maybe only load things near players
If you use generated planets, just do not load things that arent close to the player
The server can load everything that is close to a player
Server will create loaded regions around players right ?
and its moves with players
You would code that in the server
hi everybody i need help i have my prefab and i have attatched my script and in that script i want to put a reference in my public GameObject and my another script but if i try to do so it says Type mismatch. anybody knows how to fix it?
Sorry that was kinda vague and confusing. Show the details of what you're trying to do
so i have an ammoBox prefab that have script attatched to it, the script have a public GameObject in it so i want to put my game object in there in the inspector but if i try to it says Type mismatch.
what game object?
what are you trying to drag from where to where
is the prefab in file try to reference gameobject on scene?
from my assets
show screnshots
ok
sounds like whatever you trried to drag was not a GameObject
here when i try to attatch the shooting script sorry for making it confusing now i want to drag the shooting script in there but it says this
Looks like you had previously dragged something there and you have since changed the type of the field
so now the type is a mismatch
But - why is it called "Shooting script"? Did you try to drag a script in there?
ok so this is already diverging from what you said before
which was "the script have a public GameObject in it"
So please share screenshots and code and all relevant details
show the object you are trying to drag in here
this is the thing i want to drag in there (it have the shooting script attatched to it)
This looks like an object in the scene
prefabs cannot reference objects in scenes
oh
it is
Hey guys ^^
Anyone know how to make something similar to math.distance but with quaternions? I need to know if the rotation reached it's target, but I'll probably never get the exact value, so I need an epsilon.
oh well x) thanks
https://docs.unity3d.com/Packages/com.unity.mathematics@1.3/api/Unity.Mathematics.math.angle.html if you're using Unity Mathematics
so how can i fix that? do you have any idea? thanks for the help btw
I have no idea what you're trying to accomplish so I can't give any advice
You're foreseeing like an expert ^^ That was my goal
so i need to attatch the shooting script that is on the pistol2 in the Hiearchy to the field Shooting Script in the inspector
that's the how you're trying to solve your problem.
I want to know what problem you're trying to solve
Is this just supposed to be creating an ammo pickup for your gun?
The ammobox doesn't need a reference to the gun script to do that
i have the bullets mechanism in the shooting script and im increasing the bullets from the ammobox script
yeah but that;s a backwards way to do it
so i want to increase bullets when is the ammobox collected
the player should just detect that it walked over an ammo box and add the appropriate ammo to the appropriate gun
the ammobox itself doesn't need to reference the gun
if you REALLY must do it that way, you can make the assignment at runtime whenever you process walking over the box
thanks now i have an idea how to do it by another way thank you.
a quick question from yesterday, as I’m still not sure. If I have my kinematic rigidbody.MovePosition(pos2) from pos1, and pos2 touches a wall, is the timeline:
FixedUpdate:
-MovePosition to pos2
-Simulation generates contacts at pos1
-Calls OnCollision callbacks for contacts of pos1
-Update()
-Update()
…
-Update()
-FixedUpdate()
-Physics Similation starts at pos2, makes contacts for pos2
-Collision callbacks for touching walls at pos2
Is this correct? or no?
Is there any dynamic rigidbody involved here?
no
There will be no OnCollision callbacks then
all gone. but full kinematic contact
which seems to give OnCollision callbacks anyway
yeah, i think full kinematic contacts was added so you can use kinematic rigidbodies with a custom physics system, or custom character controller, and still get callbacks
i’m trying to figure out grounding check timing, since I have my own new pseudo physics engine, so I have more ability to screw around and customize
I probably want to do all my grounding checks at the start of fixedUpdate, but some of the knowledge isn’t quite well-timed
like, right now I check OnCollision checks to see if I am touchings wall/floor, jumpable ground, spikes, slippery floor… And I think all of that is just happenning at the wrong time because it uses last frame’s info
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I’m trying to figure out how to do a ground check using contacts in 2D, so that all my info is up-to-date at the start of a FixedUpdate. Is there a way to get contacts like this?
My concern is GetContacts get contacts from last physics update, which is a frame late.
ship must rotate around planet. Ship must launch into space upon pressing space. ship must rotate clockwise if top half, counter clockwise if bottom half. Ship is kind of doing that but also not, it is getting confused and flipping variables and stopping after hitting 360 degrees.
https://paste.ofcode.org/33byF6CSTiE3NdTcBnssWNA
https://paste.ofcode.org/BS7AM4d28MbGddhVCpGCcb
probably easy fix but braincells are minimal at the moment
in 2D, if I use OverlapCollider and Collider2D.Distance, can I just recreate the same information contained in a Collision2D, but at any time?
can I run the same async function on two separate threads?
I presume so
actually, how do you figure out when you have multiple points of contact between two colliders? To get several contact points?
I think you can do getcontacts?
idk if there can be out params for this but its a start
from what I understand, GetContacts gets contacts as of the last physics frame
I need to know what it would look like right this second
is that an issue?
yeah, i’m running a custom physics simulation
ohhhh
well you can do overlapboxall, and that puts everything overlapped into an array
if I understand your earlier questions right
the weird thing in fixed update is that contacts i think are generated from your position at the start of the physics simulation for kinematic RBs?
maybe?
I can use OverlapCollider to find all colliders
the issue is if I have that red circle with multiple points of contact, I need to know each point of contact
it should put them into an array?
unless this isnt anything to do with the Physics2D class, even on the script end
well now you have an array of colliders, and you should be able to GetContacts or something similar on each of them
GetContacts gets contacts as of last physics update
i need contact points as of right now, after colliders have all been moved
huh
my rigidbodies are all kinematic right now
so if I set .MovePosition to pos2 in FixedUpdate, then I only get contacts generated for being at pos2 after the NEXT fixedUpdate
actually, maybe the GetContacts methods are different? one doesn’t specify getting contacts from last physics update.
is it possible to have a if statement go across multiple methods, i have a if statement and i need multiple methods to run under the same condition and i don’t want to have to put the same if statement in each method
store the result of the condition in a bool field
or just pass the result of the condition to the other methods as a bool parameter
oh parameter, true
Hi
I am trying to save playerprefs in android upon calling OnApplicationQuit() or OnDisable() or OnDestroy()
Currently saving via OnApplicationQuit() but did try all others too
Upon quitting application via Exit button working fine
but if player is swipping up the application playerprefs not storing
Can anyone please tell me why and how can I fix this?
You may not receive an OnApplicationQuit message at all here.
Consider saving when the application loses focus.
yeah I think OnApplicationPause() might work here
but yeah prob want pause
On Android, when the on-screen keyboard is enabled, it causes an OnApplicationFocus( false ) event. If you press Home when the keyboard is enabled, the OnApplicationPause() event is called instead of the OnApplicationFocus() event.
Yeah, Thanks bud🙌
OnApplicationPause() worked
I want to create some helper function in unity. i will put them in a script (ex: helper.cs). i will use these functions in many other scripts. how should I implement that helper script? First thing come to my mind is put all functions in helper.cs in a class and create a reference to that class whenever I want to use them. Is this the right way?
make them static methods
Precisely. You make something static when it doesn't need to be called on a specific instance of its class
Mathf is just a pile of static methods, for example
You can also use the static keyword on the class itself to make sure that every method on it is static
Mathf itself is not static and that angers me
it's also a struct
I was about to say that it's a static struct. Wrong!
I remembered the struct trivia, but not that it's not static...
If you're using it often, you can try declaring it with using static. That way you can refer to static methods without referencing the class itself.
You may also be interested in extension methods.
They let you add new instance methods to an existing type.
public static class MyCoolExtensions {
public static Vector3 Halve(this Vector3 vec) {
return vec / 2;
}
}
for example
new Vector3(1,2,3).Halve() returns [0.5, 1, 1.5]
I literally forgot you could do this 💀
What would be the best way to determine if an object can "see" a light? like not specifically the light source, but the light given off from light sources?
I know i could probably do something like a distance check from nearby light sources to see if their light would be visible from that range, but that doesn't really account for possibly seeing the light shine on a nearby object or whatever.
This is for a horror game where ideally I'd like enemies to react to seeing light. I've already got a shader that can do stuff if light shines directly on them, but that shader doesn't really apply to this problem.
If there's not really a performant way to do this, i'll just fake it with the distance check, but if someone happens to know how one could achieve this behavior that would be great
oh thank you guys
btw, i often get lag on VS while using Unity. don't know if this is a software problem or my CPU is not strong enough. I am not even working on a complicated project, I just create a Tilemap and 2 scripts but it get lagged every time I made change to the scripts. I'm using a Dell Laptop.
A really cute way is to give the enemy a camera - low res with some postprocessing perhaps to create a texture of white/black pixels and then a compute shader to count the white pixels? Probably kind of slow but if there are only very few enemies at once it might be workable.
should only be a couple at any given time, i'll see if i can make that work
Do you see the line that says Page File? Do you know what that means?
i just gged it
In computer operating systems, memory paging (or swapping on some Unix-like systems) is a memory management scheme by which a computer stores and retrieves data from secondary storage for use in main memory. In this scheme, the operating system retrieves data from secondary storage in same-size blocks called pages. Paging is an important part of...
If you use real-time global illumination, you can sample that
Now do you understand why your system is lagging?
this is a common challenge. I think the last time we had that question on this channel, the guy was using some Light module/engine that is builtin in unity for that sort of thing. Might be worth looking into
although, this would be for figuring out how bright a point in space in, rather than for testing if someone can see the light cast from a specific light source
I did also implement that. Enemies shoot rays forwards and see if there's a clear path to a light source (e.g. a flashlight with a spotlight on it) from where the rays hit
tried this a while back with render texture and read pixels but gave up half way. Was trying to do Shadow/Hidden feature like Splinter Cell
so, very primitive ray-tracing...
it’s raytracing with one iteration
If you want to know how bright an area is, then sampling light probes with baked + realtime GI works reasonably well
at least that is what box wants i think
I tested this pretty thoroughly at one point, but it's been a hot minute and I didn't write anything down..
does work with realtime lights too?
That's where the realtime GI comes in
It affects light probes
Although it won't be completely accurate, since you're measuring how much light is bouncing off of surfaces and affecting the probes
You probably want something more...reliable, anyways
idk how unity implements light, but if they have any collider-like functionality, this would be trivial. You give an invisible light to the observer, and see where it intersects an actual lit zone
It can be hard to tell what is "light" and what is "dark" when you just use the light probe values directly
what would that be ? (something more reliable)
might need to revitalize this project if I can get this probe thing going.
the way box describes it, it looks like he is considering this as either binary (light yes/no) or something with a simple threshold (light > value)
in this case, you'd not be messing with light probes at all
you would just do physics queries for the relevant lights
I have not found a way to sample probe volumes yet, so I can't switch to those 😦
yeah, i would tackle this from a physics perspective and not a lights perspective. unless the Lights module specifically has like a perfect method for this
this would be ideal, I think.
that just gets the lightsource rather than the light itself. for example a player hiding behind something shines a flashlight across the room to a wall that the enemy can see, i'd ideally like the enemy to "see" that light shining on the wall.
yeah, raycasts are how I've accomplished exactly that
and it worked very well
I believe I raycasted from the flashlight to the wall
then raycasted from the wall to the enemy
and then calculated a score based on how well that second ray lines up with the enemy's forward vector
(with some randomization of the angle)
ah yeah, that sounds like it would work pretty well
If I have a list of GameObjects in the scene, the only way at runtime to check if they are a instance of a prefab, is to have a component on each one with a field referencing the original prefab. And check that instead of the instance, right...?
The field would wind up referencing the object itself
Why do you need to know if they're an instance of a prefab? What are you trying to do?
Is there a 3D alternative for Physics2D.Distance?
I am trying to play FX at instance of certain prefabs
What does being an instance of a specific prefab mean? That the object is a certain kind of unit/enemy/item/etc. ?
I do not think there is.
I'm wondering if your criteria should be something other than "every object that's an instance of this prefab"
but that might just be the case!
Any gameobject with a specific component. I put them in to a KDTree along with some meta data about them. And then query the KDTree with search conditions.
What exactly you are trying to do. It seem overly complicated.
I'm not following.
I've done VFX spawing/managing and never I had to do something even close to that.
I just need to be able to check if a GameObject is a instance of a prefab 😭
Basically the FX artist setups a condition "Play sound x when the player is within 5 meters of prefab Y".
Why does it is important to know it is a prefab ?
It makes no sense.
Just instantiate the thing.
Whenever you need it.
Because I need a way to specify what the play at? Like if they want to play Birds_01.mp4 at the location of any PineTree_01 prefabs that are in the scene
The system I loved the most was using a ScriptablObject wrapper around the VFX that specified the meta data.
You have your answer with my previous comments
An alternative, is to create component such as VFX Spawner.
They hold all the require meta data and manage the lifetime of the VFX.
Sorry, which ones?
The system I loved the most was using a ScriptablObject wrapper around the VFX that specified the meta data.
I see, that doesn't solve my issue at all though...
How so ? You specify where to spawn, what is the parents, what is the duration, etc.
Would Vector3.Distance work for you?
It is not the same
I am trying to specify the where to spawn, which in this case, is at any instance of a certain prefab.
Enh ?
I know, that's why I asked if it would work for them, not say it is a direct alternative. It would need some finagling
Why would be the where an instance of a prefab.
Here ^
Just make a component in your tree prefab "VFX Spawner"
Or, make a system to register points in your scene
Maybe something like a AudioSpawnPoint which contains a enum that you can filter on
A VFXSpawner per doesn't work for this for a number of reasons, not the least of which is it has poor performance at scale.
I could register components with a manager component, but that doesn't solve the issue of needing to know if a specific component is from a prefab, just moves the problem point.
And a enum could work, but isn't really reasonable to ask the FX artist to edit some code every time they have a new scenario they want to spawn things in.
It isn't the end of the world if I have to have a field on the component of each instance with a reference to the prefab (set at edit time, on the prefab). Just was hoping there was a more elegant solution.
VFX Spawner are highly scalable depending on how you code them. If they are not, it is because you made them not performant. Component without Update function are basically free. (They do not need one necessary) And if they do, they can be culled from millions possible way; You would have maybe 10 components actives at the same time.
Trying to know if component is from a specific prefab at runtime seem to me like a fundamental error. It seem obvious to me that a situation where want to change the prefab, have a prefab alternative or use no prefab could arrive. In fact, I have seen it numerous time.
Also, you should note that LD and LA are more than able to set an enum variable on a simple component or add one. And, if they are not, and they are using a prefab, it is hyper simple for you to do that.
If they don't have a update loop, then do you have some sort of manager then? How does it access them and activate them? How does pooling work? Etc. That is beside the point, this is just part of a larger system that provides a API for data about the world to multiple systems. FX, AI, Gameplay, etc.
We have ScriptableObjects that contain conditions for when to spawn FX, and what FX to spawn. So, we only ever want to be using prefabs.
Whether a artist can and whether they should are two different things.
hey I have random planet generation and just wondering but I plan to use roughly 200ish different planet sprites for generation, my question is, is there a better way than making 200+ prefabs for it to go through randomly in an array when generating? just wondering
Procedurally generate the sprites?
yeah I mean I might have them all same size or different size, I have base generation done that's fine, but just wondering if there's a way to swap sprites when generating next planet to not impact performance at all
or not as much as making a crap ton of prefabs I mean
No, only because I'm looking for the shortest distance between two colliders.
I figured it out using some custom code...but I wanted to be sure there wasn't a built-in method for it first.
Yeah, which you could do with Vector3.Distance
It would require some math around it though
But if you got it figured out then that's good
If you have no update loop you can use a manager as you said, or events.
Pooling is a non issue and is trivial to do here.
It seem to me that you already have the spawning parts figure out, which is the only specific part for the VFX. The target part can definitely be agnostic of any system. A simple component with a ScriptableObject/Enum can do the work here. Heck, it could even contain no data and just serve as a mark.
It is true that whatever you can do and what you should is different. However, it is obvious that you should not, ever, use the fact that something is part of a prefab as a way to mark an object. Your example is prime example of that. Your object is named PineTree_01 which means that there is a 02, 03, etc. If an artist add a new prefab, then it wont be register in the system and they would not be able to even know that there is one. An other example would be if an artist want to note a specific points in the prefab, not the root of the prefab, then they wont be able to do it. I would say that it is also possible that an artist would want to add a VFX on only specific instances of a prefab and not on others. This is without talking about the fact they might want to add a VFX on an object that is not a prefab.
You can swap the sprite of a spriterenderer at runtime if you ask. You could also create a tool to make the prefab for you if you want if you prefer to use prefabs.
I mean, yes... It does ultimately utilize Vector3.Distance; but there are other calculations that have to happen before that. Hence me wanting to know if it was already built-in.
Yes I understand. Which is why I said you would have to do math around it
No, there is no built-in way, which you were already told
Sorry, for the confusion
Closest thing to 3D version of Physics2D.Distance that I can think of is a combo of Collider.ClosestPoint + Vector3.Distance
Physics.ComputePenetration might be useful too
Kinda what I did, but I use the bounds instead of ClosestPoint.
i think ComputePenetration is the 3D version of .Distance
idk much about 3D tho, so I could be wrong
the difference is idk what computepenetration does with colliders that are separated
I'm completely fucking baffled. Anyone care to tell me how these two strings aren't equal? I literally copy-pasted this string into two different variables and they are apparently not equal. Did strings suddenly become reference types in C# when I wasn't looking
If I put in some random string like "dog" it comes up as equal
but when it's a file path it suddenly decides "I've never seen two more different strings in my entire life"
Hmm could the double slash mess it up somehow?
i can't reproduce the issue in dotnetfiddle 🤷♂️
But they both have them
did you manually type the strings or did you copy/paste them?
Both
I literally typed out the exact thing character by character to make sure it matched the one above it
hmmm aren't string literals interned? so they should even be the same reference
try printing the length of the strings and make sure there isn't somehow some 0 width character in there
how
I fucking copy pasted you
There's a fucking ghost in my string
what are you
Looks like when you copy from there it adds an escape character to the end
Okay, I have exorcised the invisible nothing character from my text and they are properly matching.
Now, back to the original problem this was meant to debug, why the fuck is this in my file system and how do I kill it
but that's a problem for tomorrow digi
and why the hell didn't Trim() catch this
Could it be a character that couldnt be displayed? If you print the unicode im curious what it is
https://learn.microsoft.com/en-us/dotnet/api/system.string.trim?view=netstandard-2.1
Starting with the .NET Framework 4, the method trims all Unicode white-space characters (that is, characters that produce a true return value when they are passed to the IsWhiteSpace(Char) method). Because of this change, the Trim() method in the .NET Framework 3.5 SP1 and earlier versions removes two characters, ZERO WIDTH SPACE (U+200B) and ZERO WIDTH NO-BREAK SPACE (U+FEFF), that the Trim() method in the .NET Framework 4and later versions does not remove.
Some OS localizations are pain in the ass
The other day I had to debug an UE4 issue where 2 spaces were not the same in the french locale. Apparently the organization responsible for deciding on characters decided somewhere in 2017 they want several different characters for spaces in french language specifically.
And since we were using an older UE version it wasn't prepared for that.
File system's haunted got it
kk
this is a certified french language moment
i can completely believe it
So I have a circlecast2D and I got it working as I want but I want to add one more function. I want to make it so that the render line gradually grow from the origin point to the end point. Not instantly rendering. Im not sure if I should be trying t mess with the circlecast2D or the render line. Ive tried both ways but with no luck. Ive looked online and did not find anything helpful but maybe I dont know what to look for. If anyone has any good ideas or resource I can check out that would be awesome, thank you.
I'm just gonna slip this in: https://docs.unity3d.com/Manual/physics-multi-scene.html. Maybe it could be better than using multiple circle cast for complex trajectory.
Thanks @steady moat I'll check that out.
Am I misunderstanding "OnValidate"? I thought it's meant to be called whenever something in the inspector changes?
Right now it only calls if I use "Ctrl + Z" to undo a change, any manual changes to things like collider size doesn't appear to call it?
It's only called when the component properties are changed iirc.
So changing another component shouldn't call it.
Oh.. I thought it was tied to changes on the object itself but that makes sense then
What would be the best way to track if collider sizes change while in the editor then?
actually 2 secs
2 seconds passed
I have my own Update function in an editor script which I can just use there then
Yeh registered to "EditorApplication.update" I'll just do it in there
Initially I wanted to only check when there are actual changes, but I guess I'll just have to periodically check instead
any able to give me a hand? i'm an artist that knows very little about code but trying to create a power jump
i got the jump working but i can't figure out how to reset the value of the power jump after he lands
Hey, im trying to get realtime data from a server/network and i dont know which way is best. I know something about REST api's or websockets. does anyone know which one is best to use? or more options? :)
web server? dedicated server w/ remote access?
TCP sockets should be enough for just barebones connectivity. Really depends on what you're doing on the grand scale.
i have a problem where unity randomly freezes when i enter play mode. there does not seem to be any kind of pattern to this, it just kind of happens randomy. i suspect it's something to do with this script.
You should upload it to a real paste site. It makes me download it to read the second half
i think you can click here
try running the profiler when you start the game
idk if the profiler will lock up either, but it should give you a good idea as to what's happening
i bet it will lock up but i'll see
You can't do that on mobile.
i linked the pasteofcode link there now as well
When it freezes, break with the debugger and see where the execution is.