#archived-code-general
1 messages Β· Page 173 of 1
you assumed, and you were wrong
Oh no, it only substitutes the length minus one necessity.
You'd still need to resize the collection
its just the last index
i get it
so array[^3] is basicyl array.length - 3?
i alredy saw the π― so i alredy know, i wont try it
You could possibly just use overlap box to see if anything is in the area, but im unsure what method you are originally planning to check with since you said something about the hit point - collider.extents.
Oh I zoomed into the image
Yea that's really about what I'd do
Boxcast?
@winged mortar first time I'm hearing of it o_O
I assume not a boxcast since itd essentially check if the object could be spawned along the entire distance rather than at the furthest point of the raycast
If you are standing beside something it's possible to hit that object, even if you're looking into an open area
If you are trying to place it next to a corner, you'd have line of sight yourself but the boxcast might get stuck on the corner
Depends on if this is relevant for his game

That's why I was first thinking of a raycast to evaluate an approximate distance to an obstacle and work with further checks from that point on
and that's why I was also going to decrement half of the height of collider box from the raycasthit2d.point to not clip into a wall
and then start checking for overlaps
Works fine but you can't guarantee your position to be perfect
Honestly I'd try boxcast, see if it works with your current setup
And then try to do it yourself
I think you'll have to use more than the height, so it shifts over towards the player in the reverse raycast direction by the entire extents of the object
Basically height and width
I was hoping to take as small increments as possible in reverse direction, but that is rather, a secondary concern
Okay, I'll read up on boxcast and think of how to handle it
it's basically just lots of geometry. I was just hoping there's some bigbrain way to handle it XD
@winged mortar From what I'm reading about boxcast - it may actually make my life easier
Thanks, guys
https://hatebin.com/cbtoqvysbz
I'm generating a mesh for a subdivided quad and tried adding backface triangles (see: second for loop), but for some reason my normals(?) are going all out of whack. Any clue what could be causing this? It works fine with only the front facing traingles
These are the normals without backfaces vs the normals with.
I imagine the issue is that it doesn't know which face to use to generate the normals associated with a vertex, and you will need to specify the normals yourself
Oh lord alright
+ mesh.normals = Enumerable.Repeat(Vector3.up, vertices.Length).ToArray();
- mesh.RecalculateNormals();
and it looks good
this would also make the downwards facing tris have their normals face up, right?
Yes
not that the visuals matter, just clarifying
Hello! What is the recommended way to run a static method before the editor stops play mode. The static method is inside a static class, and ideally I would like to avoid having to have a monobehaviour in my scene, since it is for editor only purposes.
first time seeing Enumerable.Repeat(), that's interesting
Subscribe to playModeStateChanged from something like [InitializeOnLoadMethod]
Thanks for the answer and the references :)
It's not the most performant, but it's certainly a lazy way to get it done π
Ah, when I change the mesh vertices I also recalculate normals
So it looks fine when freshly generated, but gets screwed the second I start trying to change it
The vertex normals shouldn't be straight up when you've distorted the mesh, so annoyingly you'll have to calculate them
That sucks, I can't implement that, would take too much processing
I have another way I can do the thing I was trying to do
Why? It'd take the same amount of processing it was previously doing with RecalculateNormals
So it's fine, I was just hoping to get away with raycasts
oh would it?
I mean, RecalculateNormals is calculating the normals, so yeah, if you do it yourself it's gonna be the same kind of impact π
do you by any chance have a useful resource for this?
im guessing i only need to calculate the normals for the first half of the tris and set the other half to Vector3.up or something
nevermind, got GPT to do my work for me
should uh probably do some research on it later
what did it come up with, I am interested to know if it failed
That's pretty similar to what I did:
// Normals
normals = new Vector3[vertices.Length];
for (int i = 0; i < triangleLength; i += 3)
{
int i0 = triangles[i];
int i1 = triangles[i + 1];
int i2 = triangles[i + 2];
Vector3 a = vertices[i0];
Vector3 b = vertices[i1];
Vector3 c = vertices[i2];
Vector3 n = Vector3.Cross(b - a, c - a);
normals[i0] += n;
normals[i1] += n;
normals[i2] += n;
}
for (var i = 0; i < normals.Length; i++)
normals[i] = normals[i].normalized;
What are othey ways for accessing variables from another script? Referencing through "GameObject.Find()" and then "GetComponent<>()" is tedious and becomes quickly messy in the code. Inheritance of multiple classes is prohibited. Static variables as i figured out recently are quite dangerous to use. So what are the other ways?
i told it to only worry about the first part of the triangles array, since i dont care about the other half, hence the /2 on the length
Initialising the array to 0 is redundant, C# does that already
oh the default value for a created Vector3 is 0,0,0?
hm interesting
And normalizing in the inner loop will not really produce much value. Inigo Quillez's article on the topic goes over it
{
Quaternion rotation = Quaternion.LookRotation(-hit.normal , hand.up);
target.SetPositionAndRotation(Vector3.Lerp(target.position, hit.point, _armMoveSpeed * Time.deltaTime),
Quaternion.Lerp(target.rotation, rotation, _armRotationSpeed * Time.deltaTime));```
i have a script that im trying to make a IK procedural hand placement so if the player moves towards a wall the hand will attatch to it, and currently it works good but theres one problem i cant figure out that involves this line:
```Quaternion rotation = Quaternion.LookRotation(-hit.normal , hand.up);```
when the hand moves to the wall it never rotates flat with the normals it always is at an angle with the raycast but i want it to be flat against the wall as seen in this picture i would love a smart person to help me out
the raycast u can see is from the hand to the hit.point
The way I'd do it is find a vector opposite to the Trigger from the player's perspective, then apply it using Rigidbody.AddForce().
Simplest and roughest way you could do it is just subtract the player's position from the trigger's position.
Vector3 pushOutDirection = (other.transform.position - transform.position).normalized;
other.GetComponent<Rigidbody>().AddForce(pushOutDirection * pushOutForce);
Have the pushOutForce be a variable that you can adjust
No
They are separate, and should not be used together
It's one or the other
If you want physics, you use rigidbody
Oh, my bad, I missed that part
This issue would be simpler with rigidbody imo, but only because I don't use charactercontroller
You can use CharacterController.SimpleMove() perhaps?
That depends on what you're trying to do. Do you have an example use case?
Often you can assign the desired component in the editor
Hi, I'm having a problem with inherited class variables, it's probably a simple problem but I'm not experienced with interfaces and properties.
I have an interface IInteractable with this property:
bool Hold { get; set; }
The class InteractableObject inherits from this interface, and has this code:
public virtual bool Hold { get; set; }
The class Chest inherits from InteractableObject and has this code:
public override bool Hold { get; set; } = true;
The idea being that any objects with the Chest class should have their Hold variable set to true. This works as expected, but I get this error:
The same field name is serialized multiple times in the class or its parent class. This is not supported: Base(Chest) <Hold>k__BackingField
Even though the game works, the error shows up whenever I save my code. Can anyone show me how to fix it?
@knotty sun I was able to resolve my issue with the code. Thanks for your help.
You shouldn't be getting that warning, but removing the backing field should resolve it. I assume you don't need to set the Hold property, so just change it to this:
bool Hold { get; }
public virtual bool Hold => false
public override bool Hold => true
If you didn't know this, saying bool Hold { get; set; } in a class is actually just a shorthand for:
bool _hold; // backing field
public bool Hold {
get => _hold;
set => _hold = value;
}
```Unity doesn't usually serialize backing fields, which is why that warning is odd.
pretty sure you have to make the bool hold in the interface virtual as well
and override in both classes
that's how I solved it last time I did something like that, if I remember correctly
Some score variable for example. You need to access it in a couple of UI scripts, some other scripts attached to gameobjects etc. Everytime you have to Gameobject.Find().GetComponent. Or use it as a static variable and then a problem of not resetting static variables arrives when you reload the scene.
Lol no
Virtual is completely optional and only relates to the implementing class
Virtual means "I can be overridden if you want to" and what you're talking about is most likely abstract. You don't have to override it unless it's abstract
You could attach the script to a score manager game object or something, and pass this object to those who need it in the editor
If that suits your scene
Doing it like this removed the error on my side :
public override bool Hold { get => base.Hold; set => base.Hold = value; }
private void Awake()
{
Hold = true;
}
@weak dove
(I used VS auto-completion which put it like this)
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.
I suppose it's some Unity Serialization shenanigans
I configured mine and got the error only in unity as well
Then you defined that property twice and caused the backing field to be generated twice
This has been a bug in Unity since like 2016
so i have an issue, was wondering if anyone could help me out. i have a 2d character which the only way it can move by design is by shooting the floor with its gun. I want it to launch the character in the oposite direction the gun is pointing. i am using the arrow keys to rotate a pivot which has the arm and gun attached. I have an object on the gun called BarrelEnd. I am adding a force to my rigidbody of the character based on the difference between the position of the character and the 'BarrelEnd', but as its rotating the location of the barrel is not changing in the editor, even though it appears to be moving in game.. any obvious reason why this is happening?
I tried recreating what they have (i suppose), with an interface, a base class that inherit from MonoBehaviour and implement the interface, then having a class inherit the base class. I attached the inheriting component on a game object and that's when the error appear in Unity console. So idk
You can fix it by naming your properties better and/or using namespaces. You should probably do the latter in general
I've tried restarting the editor several times, didn't make a difference
See above message
What's wrong with the property name?
It is a bug in the serialization pipeline and either renaming your properties and/or using namespaces fixes it
The fact that you used the same name twice in the same (global) namespace
It's implemented from interface, shouldn't it be this way ?
But I'm not trying to have different variables. There's an interface IInteractable that has a Hold variable. Every class that inherits from this interface should have this specific variable.
nevermind did it π₯³
Hey guys im wanting to use Unity CCD to do something with a level editor that will allow players to make a level, push it and then load others at runtime of course. Does that sound like its possible using this or will I need to use something else?
Is var script = someTransform.GetComponent<Script>(); in any way slower than doing Script script = someTransform.GetComponent<Script>();?
No, it is not.
it's literally the same thing
It is only preference
Alright
You may notice when you do that, if you mouse over var it will say Script
Personnaly, I hate var. It reduces readability
Honestly i'd recommend to always use the type instead of var unless you need var for some reason
I use it only when the type is obnoxious
like
var dict = new Dictionary<GameObject, Tuple<int, float, bool>>();```
My eyes
yeh
they burn
I tried to not use tuple. Better to have struct.
I'm trying to make a 'lore entry' system for my game. Nothing too unique.
Entries will be unlocked and have a path in a tree.
I was thinking maybe each entry has a path, and when it's added, the path is either created in UI or added to the an existing sub-section.
I'm wondering the best way to do this and if resources for this exist out there?
No worries, I get it
Some libs do have long class names
or when i am too lazy to change it because VS autocompletet code π
Is there a case where tuples are interesting ?
I use them in like find the minimum or maximum in a list when I cannot use linq.
(int max, float value) max = (-1, float.MinValue);
I think I used them only for a swap method, but appart from this, i don't have much knowledge on it
Yeah, swap would be a good use case
I think the less prolific the type is in the codebase, the more appealing a tuple is
if it's literally used on 1-2 lines that's the sweet spot
Ah, like a data structure that won't be used outside a function for example ?
yeah maybe a return type for a local function or something
OK, thanks π
I have a varying number of instances of A, and I have a varying number of instances of B.
I want to store all the possible group configurations.
I don't want to store everything individually like A[0] maps to B[0], A[0] maps to B[1], A[0] maps to B[2].
What I actually want is to have something like
configuration 1 = A[0] maps to B[0], A[1] maps to B[1], A[2] maps to B[2].
configuration 2 = A[0] maps to B[1], A[1] maps to B[2], A[2] maps to B[0]
and so on, covering all the possible configurations.
Any idea?
do you actually need to store all permutations?
What's the use case here?
What are you trying to do
on a basic level you can generate all of these permutations with a nested for loop
I have an arcade idle, the user serves popsicles to customers. Theres a mechanic with a platter, the platter contains up to 4 popsicles. There are up to 4 customers. The idea is to remove a step by autoawarding whatever will yield the best final results
foreach (Something a in A) {
foreach (Something b in B) {
Debug.Log($"Permutation {a} with {b}");
}
}```
it kinda depends also if (A[0], B[0]) and (B[0], A[0]) are considered different or not
I don't understand how. If I do the above, then it'll iterate through all of A, and it'll iterate through all of B so I can map all As to Bs, but it'll map things individually.
I actually need to calculate the sum that a configuration will yield. Say we only have 2 customers and 2 popsicles. Then the (A[0]-> B[0], A[1] -> B[1] ) configuration could potentially reward $100, whereas the (A[0]->B[1], A[1]->B[0]) configuration could reward $50.
By storing the configurations and their outcome, I can sort them to determine which outcome is best and then I can serve the customers based on that.
Does this make any sense?
Sounds like you need some algorithm
thank you so much
Hey guys,
I have a gameObject which is called Player, and it has PlayerId.
It instantiates 2 prefabs which are called Character.
And Player is Character parent. And it has access to both Characters. Also as I know child shouldn't know about its parent.
Does it make sense Character have a field which stores PlayerId ?
Probably simple greedy algorithm can help you start
graph algorithm
Nah
Bi directional reference is fine, if you can manage. You can inject player reference for its children
Could you give me a reason why it is fine ?
Because it does the job π€
What gives you a restriction? If you want you can abstract your Player class so child only know IPlayer interface for example
You can use the Dependency Inversion Principle as stated by others. Alternatively, you can use an Observer/Observable pattern.
https://en.wikipedia.org/wiki/Dependency_inversion_principle
An other approach would be to "extract" the player id in an other object. By example, PlayerInfo. Then both can use this object.
Personally, I would generalize the player id in something like character id.
Yup, I was using DI for injecting PlayerId into CharacterController but then I thought maybe it doesn't makes sense Character knows about its parent which is the Player. Then in some situation I was using PlayerId to raise an event which should be handled by corresponding Player (By message bus or event aggregator).
Then I've tried to omit PlayerId from CharaterController and instead Player knows about CharacterIds and based on that, handle events. But it looks kinda stupid I guess, not sure, looks like it makes things complicated. What do you think ?
I like the second approach but do you think it is an absolute rule which child shouldn't have a reference from the parent ? I'm always confused about it and not sure about the actual reason.
What do you mean by that ?
Instead of having a PlayerID inside the character, you could have CharacterID which correspond to the PlayerID. The player would then push his PlayerID
In video game, most of the time, the clean code aspect is thrown out to some extends. This is necessary. My advice would be to not think to much about.
If you still want to make things clean, I would suggest that you never have direct bidirectional reference (No interface in between) and reduce as much as possible indirect bidirectional reference (Interface/Events). When you respect those rules, you inherently increase the modularity of your application.
To make such application, you need to heavily subdivide your behavior in such a way that the dependency graph is a tree. Doing so would result in a really more complex code though and might not be suitable for every team/person. This has the same dynamic that cohesion/coupling has.
Got it, thanks.
I also like to think: you can attempt to make your game as modular as possible but theres a certain point where you definitely wont extend a feature
Over engineering and getting the same result as a "less clean" solution has no affect, the only thing that matters is "will people pay for this"
I'm looking for some input on selecting a solution path for saving/loading game files for a new project.
I'm building a game with a "persistent" world. Each map screen (think "chunk") is generated when needed and contains some number (currently about 20x10 = 200) blocks - these blocks can be destroyable and contain resources, fixed terrain, or other navigation (ie, move to the adjacent chunk). You can travel NESW and Up/Down from chunk to chunk.
Should I just create my own file format? Use something like MessagePack/Protobuf to read/write byte arrays? Store it in json?
I'm worried about long term save file size as players build up their world.
Is this data mutable or immutable once "rendered"? Im assuming the chunks are being lazy loaded as needed, and then you wanna cache em for faster future loading?
mutable: Youll wanna make your own custom data format, because I dont think protobuff supports specific point save/editting, you'll wanna have the ability to discretely modify specific points in the data for mutations that occur in game (IE in Minecraft, you dont wanna have to resave the entire chunk because you broke 1 single block, every block)
Immutable: Protobuf should be solid
You could potentially store the "original" via protobuf, and then use a secondary "mutations" file that stores a sort of "diff" of the chunk from Old->New, so you apply the original, then apply the diff to produce the expected output.
Could also have a background process that periodicially goes and applies the diff to the original and resaves the original (and disposes of the diff) to improve speed.
Hey everyone and anyone.
Like I probably already asked before, I'm trying to make a character creation scene in unity. Right now I want to start simple to get to know how to do it, by just starting with "gender" option, male or female and a "name" textbox. I got the default male model and female model from mixamo. So UI is a button or dropdown "gender" that opens the male or female option and a textbox where you can write your name. A renderer is active that shows the model you've chosen. When you press "create character" I want the chosen model to be visable as the player model and the name somewhere saved so I can use it whenever I want in scripts.
After I've done that I want to start adding things like hairstyle, haircolour, skincolour, face variants and so on.
Can anyone push me in the right direction for this please?
a custom binary format is going to be the most compact, with MP or PB being a close second
JSON is probably not recommended.
Yeah, the only reason I'd consider JSON is debugging lifecycle. byte[] is hard to read - I'd have to make custom tooling to look at them
Maybe I should make two adapters - save both files, turn off the JSON adapter for production
Cool, I'll check it out. I'm not an expert in protobuf - I've used messagepack this last couple years
and low risk of the binary format/formatter itself containing bugs
messagepack is also good
Not sure I'm still on the MP bandwagon though because of all the aot/jit issues with android
(I'm assuming I'll have the same with protobuf though)
ie - android doesn't support JIT compilation so I have tooling to generate and include messagepack CS files in my android builds.. it's a bit of a pain in the ass and was a huge timesink figuring out this last year (probably 100+ hours just related to that)
you'll need to do something similar for protobuf
bah
but it shouldn't really take 100 hours π―
protobuf is more widely used from my understanding
It is - using it right now at work in fact lol
the 100 hours was .. the educational "journey" for learning all about the nuances of the android/google environment and getting my builds working with my ci/cd tooling
sounds like much of that knowledge can be reused?
it was.. painful.. there were very limited resources out there for my specific usecase
yeah, i "have it" now so I could reuse it
Honestly though unless you're making changes to the PB a LOT, I would just leave the source generation step as a manual step
if protobuf is likely to be similar "just different" then I'd probably just default to MP, but it would be nice to have protobuf knowledge in my personal repetoire
perhaps - there's some stuff i like to shove in my POCOs/DTOs that i had to do a little bit of backflipping for (like structured logging integration, some overrides, etc) but .. i could probably get away from that by having another poco layer without the dependencies.. ie, have a "pure" poco that's MP/PB/JSON consumable and then another POCO on top of that that just contains a reference to the smaller POCO with all the extensions and custom stuff I want to have in them.....
sigh, real coding is complicated
@leaden ice are you using PB in a unity project? any "gotchas" you've found?
seems like there's solid C# support
I think the way PB works with assemblies and namespaces in C# is a little weird from what I heard but I haven't really used it with C#
I think you get options for namespaces etc in the generator so it shouldn't be too bad
it seems fine? looks like you just define your message in .proto files and there's some tooling in .net to map your data to those messages
I'll probably stick with MP.. i suppose there's no reason to reinvent the wheel here.. I suppose I don't really have any problems with MP, just a little bit of remembered pain from onboarding it all.
Then as far as this project is concerned, I'll probably make some sort of monolithic save file with all my POCOs and just serialize the entire thing to byte[] or json and try to keep the size of it down.. like I probably don't need to track all the details of every block - like if someone's hit it 50%, I don't really need that.
This probably means I need a separate save file POCO from an in-game POCO.. ie:
public class SaveFileBlock // MP object
{
[Key(0)] public BlockType BlockType {get; set;}
}
public class InGameBlock // Hydrate this from the SaveFileBlock
{
public BlockType BlockType {get; set;}
public int CurrentHP {get; set;}
... etc ...
}
one thing to think about - I assume this is some kind of minecraft style game? - if the player can have multiple save files, you might want to store metadata about the save somewhere in order to display the save in a list of saves
yeah
you wouldn't want to load the whole world data in order to display that list
my save file MP POCO would be something like
public class SaveFile
{
[Key(0)] public DateTime LastSaved {get;set;}
[Key(1)] public string SaveFileName {get;set;}
[Key(2)] public PlayerPoco Player {get; set;} // the bulk of the data
}
oh wait, i see what you're saying.. hm, yeah
so something like
So what I do sometimes is I'll bake a header into the save file
so you can just read the header bit and ignore the rest
public class SaveFileMetaData // tiny file
{
[Key(0)] public Guid Guid {get;set;}
[Key(1)] public string SaveFileName {get;set;}
[Key(2)] public DateTime LastSaved {get; set;}
}
public class SaveFileData
{
[Key(0)] public Guid Guid {get;set;} // matches guid in metadata
[Key(1)] public PlayerPoco Player {get;set;} // bigass byte[]
}
could probably even show file size (on disk) in the metadata
so IDK how it works in MessagePack but a quick example with json would be like:
HeaderData hd = new HeaderData("Save 1", "Gary Peterson", DateTime.Now());
string headerJson = JsonUtility.ToJson(hd);
string gameDataJson = JsonUtility.ToJson(saveData);
filestream.Write(headerJson);
filestream.Write(gameDataJson);```
then the save file parser can read the header part and ignore the rest to grab the metadata only
don't you have to read the entire filestream though to just read the metadata?
ah you could read byte by byte until you've got what you need?
exactly
cool
Another option is a separate file which has data about the other files.
But that's annoying because you can have all kinds of issues
like keeping them in sync
aye, or storing the metadata in playerprefs even
yeah
they all have issues like if something gets corrupted or a user manually moves or renames files
yeah, the issue that I forsee being the big one is what do i do with invalid data because features have changed
like, i'll probably have to put some versioning in the files, make an effort at never deleting/renaming fields, etc
pain in the ass stuff
yeah you'll need versioning
if a user manually moves/renames files, well, they're on their own
the header section is a great place to put a version number too
for the save file format
yeah.. and then i'll include some stuff in the save file hydrator that migrates data if it reads older versions
of course the header format itself could change but you'll maybe commit to making only additive changes there
anyway, that's future-me problems, i'm still very much in prototyping, but this is good stuff to think about ahead of time.. i still encounter some of these problems with space game and have a lot of dangly-data-appendixes in the system
like i found out sort of the hard way that serializing/deserializing enums in unity is ... a minefield
I have this cutscene system where the writers can write cutscenes on the admin tool and the cutscenes are delivered to the clients via messagepack.. but it's allllllll enums. I removed a couple of old values that we didn't use anymore and it fucked up every single cutscene in the database - the wrong images were being shown, the wrong music was playing, the wrong props were being displayed, the wrong animations were playing... what a disaster day that was
does messagepack have an option to serialize enums as strings instead of ints?
yes, but .. I don't π
the cutscene data represents the largest chunk of data we send to clients.. back before I was versioning it and caching the cutscene data on the clients, every time a client would connect they'd get the entire cutscene database.. even serialized to byte[] it was like.. 30mb?
caching it solved that problem almost by itself but still, new client installs need all that data.. so.. serializing a ton of enums as strings would bloat it pretty badly
data looks like that
then you need to be careful about changing enums destructively and versioning the format whenever you do
yeah, that's one way - my new way of handling enums is to manually assign the underlying int (and never change it)
like this
right I call that "being careful about changing enums π"
i am currently doing the unity junior programmer course, i've completed till create with code - 1, just wanted to know if its worth the time and effort learning from that course?
oh wow I thought I was yapping on in #archived-code-advanced .. oops
In general your best educational path will be to "do" - make apps, try to do things, and supplement that with the courses. A lot of knowledge is out there, but imho it's hard to retain it until you're actually trying to build something. Just passively watching a course and even taking notes is not really great for retention and deeper understanding.
Start with a simple game (like pong, pacman, donkey kong, happy color, etc) and see if you can get it all working. You'll find pretty quickly that you're unable to do something pretty basic - come to discord for help, and watch the videos and do the courses in your non-working time
there's a way to see FPS in exported game?
sure - add a UI element and display it there
you can also attach the profiler, or possibly use utilities included with your GPU (like nVidia overlay)
another question, and i know that is no the topic
dou you know about post processing?
go ask in #π₯βpost-processing π
can you help me if i ask there?
I won't commit to anything
hi guys, i wonde can players save files from game asset to their desired location, forexample backgrounds of my loadscreens i want to let players save and use it wherever they want ?
Nothing stopping you from allowing this, sure
is there any permission i request from player like mobiel os's or just give him a button and save ingame folders ?
or may i open the folder automaticly
yes some platforms requires special permission to access certain parts of the filesystem
Hey I was trying to get ads running and ran into this error, anyone know how to resolve that?
thanks
This only happens when the build settings are set to android, what is the platform I wanna build on though
do you have all the android SDK stuff installed?
I'm trying to make a 'lore entry' system for my game. Nothing too unique.
Entries will be unlocked and have a path in a tree.
I was thinking maybe each entry has a path, and when it's added, the path is either created in UI or added to the an existing sub-section.
I'm wondering the best way to do this and if resources for this exist out there?
these are the build settings Im trying to use
I made a new project from scratch so there is 0 code from me in it whatsoever, it just fails installing the package in the first place
I'm tryna make use the animator component for a state tree for a boss im working on. Issue is, the animation's OnStateUpdate() is called every frame, rather than like FixedUpdate, and no FixedUpdate() alternative exists as far as i know. How would I achieve this?
nevermind
can someone help me with this question
I don't knw where to post this, but what is this and why does it keep showing as errors? I just want to remove it
the little red thing on the left side
It's the Git integration in the IDE. Here it tells you that one or more lines have been removed compared to the last version of the script you committed.
I've never seen this until I reinstalled Visual Studio on this
Latest update feature, most likely. VS Code has these indicators too, but they were added earlier compared to VS
how do I turn this off
Shouldn't raycasts ignore the collider they start in and/or the collider of the object the script is on?
Somewhere in the settings...

only if you enable that behavior in the physics settings
you should still use a layermask even with that setting enabled though
I can't find whatever any of this is
I have multiple npcs with the same layer who should get in the way of each other so I believe I can't use layers for this, also I couldn't find a setting for that in Physics settings, but I found this in the API "Raycasts will not detect Colliders for which the Raycast origin is inside the Collider."
I can't find any more info on this apart from this one page, so I can't disable it
and are you sure that the raycast origin is inside of the collider?
Oh dam, it is on the collider. But I still couldn't find that setting if I need it to not hit the transforms collider
turns out it's a 2d only setting and 3d only has a semi equivalent setting for mesh colliders π€·ββοΈ
but it's set to the behavior you want by default anyway
Odd it wasn't working for me then, anyways I just move the collider so that the ray start position isn't on the collider but in and it works :p
When you commit the change, it will go away. Sorry that's all I know about it
Thatβs a lot of scripts that have that
the page you linked says how to disable it π€
There is only one page on the internet that talks about it, and when I follow it, nothing it says is there
I restarted and I will try again because maybe it was a glitch
that feature is no longer a preview, i think this is the one u are looking for now
Tools > options > text editor > general: Track changes
Though if a lot of scripts have this, are you commiting your changes properly?
So you have a lot of uncommitted scripts π€·ββοΈ
public void SwitchRooms(GameObject newRoomPrefab, Vector3 direction)
{
Transform newTransform = curRoom.transform;
newTransform.position = transform.position + 6 * direction;
GameObject newRoom = Instantiate(newRoomPrefab, newTransform.position, newTransform.rotation);
StartCoroutine(MoveRooms(newRoom));
}
private IEnumerator MoveRooms(GameObject newRoom)
{
Vector3 newRoomFrom = newRoom.transform.position;
Vector3 oldRoomTo = newRoomFrom * -1;
for (float i = 0; i < 1; i += Time.deltaTime) {
newRoom.transform.position = Vector3.Lerp(newRoomFrom, Vector3.zero, i);
curRoom.transform.position = Vector3.Lerp(Vector3.zero, oldRoomTo, i);
yield return new WaitForEndOfFrame();
}
newRoom.transform.position = Vector3.zero;
Destroy(curRoom);
curRoom = newRoom;
}
```
I'm I have 2 rooms, one in a prefab that gets instantiated to `newRoom`, and one kept track of in `curRoom` (a variable in the class). I just want this function to slide the new room onto the screen and slide the old one out and destroy it, in about 1 second's time. For some reason, this instead takes about 0.1 second, and at the start the room get teleported to (-.99, -.19, .01) then the new room slides to the center while the old room slides about 1 quarter unit diagonally... anyone see what I could be doing wrong? Is there a better method to this?
Hey I made a jetpack code and for some reason it doesn't work the same. When I'm playing maximized it works perfectly, but when I play focused or on the exported game, it works incredibly buggy, playing audio and particles but not doing the jetpack thing. If anyone knows how to solve this sort of bug where it plays well somewhere and wrong somewhere else, please help me π
pretty hard to suggest anything based on this alone, could be FPS related, could be values that existed in your editor but not a build. You'd probably have to show what you did
Respected, I am trying to rotate the camera around a car when the user touches the screen, and when the user touches the car, then not rotate the camera, but I am not able to achieve my goal. My car layer is "Car". And the other layer is "Default". Anybody can help me in this regard? Please.
void Update()
{
if (Input.touchCount > 0 || Input.GetMouseButton(0))
{
#if !UNITY_EDITOR
ray = sceneCamera.ScreenPointToRay(Input.touches[0].position);
#endif
#if UNITY_EDITOR
ray = sceneCamera.ScreenPointToRay(Input.mousePosition);
#endif
if (Physics.Raycast(ray, out var hitInfo, Mathf.Infinity, ~whatIsCar))
{
Debug.DrawRay(transform.position, hitInfo.point, Color.red, 5f);
Debug.Log(hitInfo.collider.gameObject.layer);
// touch = Input.GetTouch(0);
// float mouseX = touch.deltaPosition.x * Time.deltaTime * _mouseSensitivity * -1;
// float mouseY = touch.deltaPosition.y * Time.deltaTime * _mouseSensitivity;
float mouseX = Input.mousePosition.x * Time.deltaTime * _mouseSensitivity * -1;
float mouseY = Input.mousePosition.y * Time.deltaTime * _mouseSensitivity;
_rotationY += mouseX;
_rotationX += mouseY;
_rotationX = Mathf.Clamp(_rotationX, _rotationYMinMax.x, _rotationYMinMax.y);
Vector3 nextRotation = new Vector3(_rotationX, _rotationY);
_currentRotation = Vector3.SmoothDamp(_currentRotation, nextRotation, ref _smoothVelocity, _smoothTime);
transform.localEulerAngles = _currentRotation;
transform.position = _target.position - transform.forward * _distanceFromTarget; } } }
May I send the code on dm?
why? just send it properly here !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.
okok
and that command above this message is for you too, paste it how the bot suggests
a powerful website for storing and sharing text and code snippets. completely free and open source.
What do you mean?
does anyone know how to set a sprite from a sprite atlas's texture to be readable via script?
Anyone know why the camera just shows blue when I spawn in the character?
i dont specifically see anything thatd cause this. make sure you save and rebuild incase, but you can also debug in builds to see if there are any differences/errors. You'll just either have to print the logs to some text area on screen, or look at the log folder.
Okay...
You're camera is probably too close on the z axis
the default z is -10
There aren't errors. It just doesn't execute properly, might it be because screen resolution stuff?
Iβll try both
My main problem is that it doesnβt have the problem when it isnβt a prefab
and you checked there arent errors in the log folder? Also still you can debug to see what values are different/not expected in a build compared to in editor
Is the camera in the prefab or do you spawn it manually?
Ima do a new build and try
I spawn the camera with the player
The camera is a child of the player
With code or is it already in the prefab?
Already in
Ok, then make sure the camera's z is -10 or something similar
and the player is at z=0
Alr
Hey there i have problem with my Main Menu Script i followed a tuorial but i cant press ESCAPE button to open my pausemenu. Nothing happens, if i hardcode
| Input.GetKeyDown(KeyCode.Escape)```
the escape menu works. What is my Problem?
My Input Manager
```cs
using UnityEngine;
using UnityEngine.InputSystem;
public class InputManager : MonoBehaviour
{
public static InputManager instance;
private PlayerInput _playerInput;
public bool MenuOpenCloseInput { get; private set; }
private InputAction _menuOpenCloseAction;
private void Awake()
{
if (instance == null)
{
instance = this;
}
_playerInput = GetComponent<PlayerInput>();
_menuOpenCloseAction = _playerInput.actions["MenuOpenClose"];
}
private void Update()
{
MenuOpenCloseInput = _menuOpenCloseAction.WasPressedThisFrame();
}
}```
This is my MenuManger
using UnityEngine;
```cs
public class MenuManager : MonoBehaviour
{
[SerializeField] private GameObject _mainMenuCanvasGO;
public static MenuManager instance;
private bool isPaused;
private void Start()
{
_mainMenuCanvasGO.SetActive(false);
}
private void Update()
{
if (InputManager.instance.MenuOpenCloseInput /*|| Input.GetKeyDown(KeyCode.Escape)*/)
{
Pause();
print("Pause");
}
}
#region Pause/Unpause Functions
private void Pause()
{
isPaused = true;
Time.timeScale = 0f;
OpenMainMenu();
}
public void Unpause()
{
isPaused = false;
Time.timeScale = 1f;
CloseAllMenus();
}
#endregion
#region Canvas Activations
private void OpenMainMenu()
{
_mainMenuCanvasGO.SetActive(true);
}
private void CloseAllMenus()
{
_mainMenuCanvasGO.SetActive(false);
}
#endregion
}```
What do most games use to deal with ramps
Like what method
Because those things are horrible
Itβs loading the camera this time but itβs not showing the player sprite now
Whatβs your problem
Well, slope bouncing & slower speed mostly
There are other problems I'm sure but I can't think of them
Unity 3D btw
Iβm still pretty shit at programming slopes so I would look up a tutorial
Make a raycast checking for a slope or not and then mess with your code for that
!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.
Trying to make doors work with hinge joint component, normal swing doors work fine but a door that opens down like an oven door doesn't work
anyone know how to make an hinge joint door work with open down
Did you enable the new input system, or set them both to work?
both to work
You have to enable the InputAction
(InputAction.Enable())
What wasn't clear? If you have a lot of scripts with the red triangles, then you have a lot of scripts that haven't been committed
No I don't understand
Did you try this though?
#archived-code-general message
Which part?
committting
Ah... you are using version control, right? If not, do so
Committing is saving in version control, like git
What you mean? Can you show me example on my code?
I'm not using Git for this project
In InputManager:
private void OnEnable()
{
_menuOpenCloseAction.Enable();
}
private void OnDisable()
{
_menuOpenCloseAction.Disable();
}
you're sure the axis is correct?
To open down you'll want the joint set on the Z axis
yeah if i have the use gravity on rigidbody then it just falls down otherwise it doesn't move
using UnityEngine;
using UnityEngine.InputSystem;
public class InputManager : MonoBehaviour
{
private void OnEnable()
{
_menuOpenCloseAction.Enable();
}
private void OnDisable()
{
_menuOpenCloseAction.Disable();
}
public static InputManager instance;
private PlayerInput _playerInput;
public bool MenuOpenCloseInput { get; private set; }
private InputAction _menuOpenCloseAction;
private void Awake()
{
if (instance == null)
{
instance = this;
}
_playerInput = GetComponent<PlayerInput>();
_menuOpenCloseAction = _playerInput.actions["MenuOpenClose"];
}
private void Update()
{
MenuOpenCloseInput = _menuOpenCloseAction.WasPressedThisFrame();
}
}```` still my esacpe not working
Try putting a Debug.Log to see if the value is ever true
(in InputManagers Update)
I wouldn't start a flappy bird clone without version control honestly. Next to the debugger, it is the most important tool in coding.
But either way, try what bawsi said
You should look into it. If you dont, then dont be upset if 1 month into a project something gets corrupt and you have to start over from scratch. Or 3 months.. or a year
try 3 years
Deleted my post in the beginner chat to post here instead without cross-posting since this may be a more appropriate channel.
You've been coding for 3 years and never learned version control? You REALLLLY should know it by now
I'd die without git lmao
I've been coding for longer, but not used version control
just for that project
That is an issue.
Like I said, it's one of THE most important tools in coding.
I would honestly stop everything and take the 10 minutes to learn it and set it up
alright
There're guis to make it dead simple
Just having the ability to branch off for experimentation is wildly helpful
Even if not branching, just saving your work is a must
And being able to roll back to more stable foundations/at least have a way to look at your code from that point in time
How do most games handle slope movement?
This shit isn't working
https://www.youtube.com/watch?v=xCxSjgYTw9c
SLOPE MOVEMENT, SPRINTING & CROUCHING - Unity Tutorial
In this video, I'm going to show you how to further improve my previous player movement controller by adding slope movement, sprinting and crouching. (You can also use your own player controller if you want to)
If this tutorial has helped you in any way, I would really appreciate it if you...
This guys tutorials only work for the purpose of the video, I wouldnt follow a single thing from him
Ok thank you
I've been learning this the hard way lmao
Yeah
Let me see if I can find a video I saw linked covering it properly
Right now I'm trying to design a controller that would support basically Tribes-esque movement and boy howdy am I extremely lost lmao
Thank you :)
Also IDK if you saw my earlier message but I'm having a problem where my player moves much too fast if they aren't selected in the inspector
Do you have serialized or public variables that may be drawing from the inspector fields instead of the script or vice versa?
All variable values come from inspector fields, but deselecting it shouldn't cause problems...
At least it never has before
Investigating how players move in games with Unity.
Try out the demo at https://nickmaltbie.com/OpenKCC
GitHub project at https://github.com/nicholas-maltbie/OpenKCC
OpenKCC Series Playlist - https://youtube.com/playlist?list=PLFlu9cd6nGXt64a-N063t5hZdpjdIl76p
How a player moves through a virtual space is not always clear and straightforward. ...
This was a pretty good one, u could also just use the kinematic cc on the asset store
The only time I've ever had something like this happen was a unity bug when my unity crashed overnight and I didnt notice. Then opening it up again had the sameish result. Maybe restart your unity
I have
:(
Why is InputAction.CallbackContext so bloody useless... Why does it not just let you know you clicked on a ui object? Seriously unless I'm missing something the input system is purposfully stupid.
Yea I wouldnt have a clue otherwise. I'd start by debugging what related values are like your move speed or anything else. Maybe try making a new character and see if it happens on that one too. Really hard to say without knowing the exact specifics of your project
why would the input know about your UI objects? what you want is the EventSystem which is what handles translating input to interacting with the UI
if you ask the eventsystem from the input system EventSystem.current.IsPointerOverGameObject() it will give you an error
and what error would that be?
it's not referencing the correct frame
wtf does that mean?
Is that word for word what it says?
You should probably just follow a tutorial or written guide on this if you dont know what's happening
Calling IsPointerOverGameObject() from within event processing (such as from InputAction callbacks) will not work as expected; it will query UI state from the last frame
Interesting, this video seems to take roughly the approach I was thinking: compute the camera movement then implement movement as a result of that.
and it absolutely can cause an error in behavior
It goes into a lot more, at least if I'm remembering correctly like slopes and moving along a wall instead of just being stuck at an angle
Yeah in terms of projection onto inclined surfaces and such, which is currently handled by the CharacterController element for my current implementation
That is like as vague as you can be
Sorry you're right lmao
Projecting the movement onto the plane of the ramp normal
Are there any built in components in Unity.UI for pinch+zoom scrollrects?
Ok, I just - here's the movement code. I know there are errors and redundancies. Help it slope good
https://hastebin.com/share/mekoyoyino.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I don't know about built-ins, but this video shows a simple way of using the new input system to just calculate the change in distance over time of two touch points: https://www.youtube.com/watch?v=jKVTKKDr7Ak
Get the code here: https://gist.github.com/Mohammad9760/48375505c45adba807f75fd49a700494/archive/ac3cb0eb07d2079db3fad301b25d125356a2bae0.zip
in this video I'll show you how to zoom with mouse scroll and touch screen pinching using the new input system in unity!
you will learn how to setup Input Actions all with code and how to zoom a prespecti...
Ok I found my problem
When I spawn in the player character the camera spawns on the same z axis coordinates no matter what I input
How do I fix this and make it spawn further away from the player
spawns as in your instantiating it?
Yes
how can i copy a struct that is on a scriptable object class?
internet tells me structs get copied by default and classes are referenced
but when i change the value of struct in the scriptable object the one i was supposed to copy also changes
its making a copy?
whats the struct contain ?
So does anyone know how I can fix my camera
duct tape
Since it doesn't look like my question is gonna get much traction is there any chance someone knows of good resources for designing a character movement scheme in depth with all the physics and such?
public class ScytheSwingSkillData : WeaponSkillDataBase
{
//do not use this outside of slashscript for 'project organization' if you are going to use it anyways at least put it in generalstructs
public enum PositionDirection { forw, right, up }
[System.Serializable]
public struct SlashScriptAttack
{
public ListOfVector2 rotateAngles;
[Space(30)]
public ListOfVector3 rotateAxis;
[Space(30)]
public AnimationCurve attackRotationCurve;
[Space(40)]
public ListOfVector2 localPositionOffsets;
[Space(30)]
public List<PositionDirection> positionDirections;
[Space(30)]
public AnimationCurve attackPositionCurve;
[Space(20)]
public float attackBaseDuration;
[Space(20)]
public float attackBaseCooldown;
[Space(20)]
public float attackBaseDamageMult;
[Space(20)]
public Vector3 mouseCursorDirWeightMultiplier;
[Space(20)]
public float mouseCursorDirAngleOffset;
}
[System.Serializable]
public struct ScytheSwingDataStruct
{
[Header("Swinging")]
public int normalAttackComboAmount;
public int flyAttackComboAmount;
public float stopComboTime;
public List<SlashScriptAttack> slashScriptAttacks;
}
public ScytheSwingDataStruct dataStruct;
}
there aren't any classes or someting in the struct
are you changing the reference type ? cause that doesn't make a new copy
List<PositionDirection> for example
public override void InitializeSkillData(WeaponSkillDataBase skillData)
{
base.InitializeSkillData(skillData);
dataStruct = ((ScytheSwingSkillData)skillData).dataStruct;
}
i get it like this
oh
lists don't make copies?
that was the problem i guess
List<T> is a class therefore a reference type
lists are reference type
Is it illegal to bump a message from another channel?
Speaking of bumping, sorry to do it so soon but I'd love some thoughts/advice on this: #archived-code-general message (alternatively some material on designing complex movement would suffice)
You can reference your question in another relevant channel if it became buried and some time passed.
Do coding bugs relalated to the input system go here or #π±οΈβinput-system
It depends on specifics, is it a coding problem or a specific problem related to understanding how input system works.
alight then Bump! #archived-code-advanced message
When in doubt post entire question first ask later. (just don't cross-post)
The error is a method exception but my debug commands works so idk whats happening #π±οΈβinput-system message
I mean is adding a link cross posting?
When your question is still visible, yes
your issue is just likely networking related, the instance of the class not being found by the server for all other clients.
this is all on the server tho, I have an event just like it above it, that one wors well
No, another event works well, nevermind it.
I just added a null check for this event and I'm getting the message "null" but It's clearly deffined no?
This null reference exception is from the subscriber
if your delegate is null, you have nothing in the invocation list
aka nothing has done OnAuto += something
A common way to write that is just OnAuto?.Invoke(); You can use null conditional since its not a unity object
The problem here is the fact that it is null, why is it null?
I don't really wana check if it's null, I wana call it
But I can't put nothing in the invoation list because it is null
you should look at some guide on how delegates work, or experiment outside of unity in a project you can run this quickly on
that is not how delegates work
maybe refrain from that language here too :p
Oh sorry. Look at what I missed, on the script that calls it
the "subscriber"
like it ain't the delegate missing, it's the whole ass script reference
even though not neccessarily networking related then, this was still basically the issue then
the instance of the class didnt exist
y but the debug message don't differenciate between the delegate missing and the class refernce missing, so i got confused, sill mb, thank you for your help!
you had two errors. the first was the characterAutoAttack object being null where you subscribe to the delegate. since that had been null nothing subscribed to the delegate hence it being null for the second error. always start resolving errors with the first one in the list, 9 times out of 10 it is the reason following errors happen
hi, i have a problem, i have a object that travels realy fast and sometimes pass the collider, what can i do??
Using rigidbody based physics movement will probably fix it. Are you using transform movement?
yes. depending on how fast it is moving you may even need to make sure the rigidbody's collision detection is set to continuous
and if it is too fast for that then you need to not move it as fast or do collision checks manually
manipulating the transform does not use the physics engine, therefore, the collision will not occur accurately when the object intersects the other object's collider . . .
Noty what I was refering to, but thanks for the advice!
I have a question about the way I should aproach coding some pathfinding for my game
got it
for the enemies spesifically
i think it souldnt be a problem
got it thx
sure, but when you += a delegate it will not throw a NRE if it is null. so the NRE on that line could not have been referring to the event
ah, mb then, did not know that. I thought it has to do with the passed AutoInfo object since the errors started when i renamed the class, everything bugged out and then unity said, no script reference in this object because f*k u that's why xd
I want the red enemy to choose the closest target to go to, but because there will be a lot of enemies, i don't want to calculate all the distances and find the shortest one for every enemy and for every frame.
How should I approach this so it isn't very resource intensive?
Also the squares in the pic will act as distractions and will pop on and off when the player wants. How should I inform every enemy when they acitvate and deactivate without being resource heavy?
(I don't want the specific code, just the way I should approach coding it)
there is something like pathfinding, its coll navegation i think
its a bit complicated but i think it should solve your problem
sry, another question. its recomanded to have Interpolate option to Extrapolate in my case
does any knows what this error means:
NullReferenceException: Object reference not set to an instance of an object
UnityEditor.Graphs.Edge.WakeUp () (at <50dee61f6c6e4b4185702f2b27b5e2bf>:0)
UnityEditor.Graphs.Graph.DoWakeUpEdges (System.Collections.Generic.List1[T] inEdges, System.Collections.Generic.List1[T] ok, System.Collections.Generic.List`1[T] error, System.Boolean inEdgesUsedToBeValid) (at <50dee61f6c6e4b4185702f2b27b5e2bf>:0)
UnityEditor.Graphs.Graph.WakeUpEdges (System.Boolean clearSlotEdges) (at <50dee61f6c6e4b4185702f2b27b5e2bf>:0)
UnityEditor.Graphs.Graph.WakeUp (System.Boolean force) (at <50dee61f6c6e4b4185702f2b27b5e2bf>:0)
UnityEditor.Graphs.Graph.WakeUp () (at <50dee61f6c6e4b4185702f2b27b5e2bf>:0)
UnityEditor.Graphs.Graph.OnEnable () (at <50dee61f6c6e4b4185702f2b27b5e2bf>:0)
does it work for 2d though?
It's an Editor bug, ignore it.
ayt thx
Guys, can I buy some developer license or something so that the apps I create stop being picked up in windows defender as unknown app?
you can use a cast or overlap method to collect enemies within a certain range, then loop to find the closest enemy. this limits searching a collection of enemies to a given range instead of every enemy alive or in the scene (view)
an alternative is using a trigger collider that adds enemies to/from a collection when they enter/exit the trigger collider. then you run a loop to find the closest enemy
if you're worried about it being resource intensive, you can run the distance check (on the collection) on a timer or ping every X amount of frames or X amount of seconds. that way, you can increase or decrease X when ever you want . . .
Should I use Coroutines to set the time limit for the distance checks?
or are there other methods?
you can use a coroutine but using Update should be fine. that'll give you more flexibility to stop/pause the searching and/or distant check code if needed . . .
How can I have something in Update() that runs every x amount of frames?
count frames, and only do work every nth frame
likly more useful to do it based on time and not frames though
if ((Time.frameCount % 8) != 0) return;
hmmm I have never heard about this. Where can I read more about it?
yes but the .frameCount
so like (n % 2) == 0 would only be true if n is divisiable by 2
Unity docs has everything
and wouldn't that be == 0 and not != 0 because we want every 8 frames?
also docs for unity things
https://docs.unity3d.com/ScriptReference/Time-frameCount.html
well no my example i was returning early
well its returning if its not 0
so skip the rest of a function
Oh yes my bad, I forgot how to read code
like if ((Time.frameCount % 8) != 0) return; was saying if its not divisible by 8 return and do nothing
thanks a lot, I really didn't want to go through the hastle of doing everything with Coroutines
i was corrected on this now i must correct others π it is the remainder operator in c# so it can return negative values
not in this case, but in general
for this purpose with positive inputs does not matter though
but yeah in general it does act different then say the same operator in like python
also @hasty plinth reason why you want it based on frames and not time?
like not do things thing every 0.25 of a second or something like that
sorry, afk. you can check the frame count but it's easier to do X amount of seconds . . .
just use a timer, when it's 0, run the method and reset the timer . . .
Oh, no particular reason, I thought that maybe frames would be easier, but other than that no reason
How could I do it with time instead of frames?
make a float field, set it to how long you want to wait
every frame subtract Time.deltaTime from it, when it goes below zero call your logic and reset it to its original value
You can reset to the original time - overage so you don't drop time too. It'll practically never be exactly 0 at the end of the timer, so it'll druft if you don't account for that.
It only matters when you reaaaaly need precision/regular timing though
For cooldowns, this would never matter
i said reset it, since its counting down from the total wait time
and the check is for below zero not zero
Yes I know... what does that change for what I said?
When it goes below 0 (which it will, as you said) you get that amount and reset it to total wait time minut that below 0 amount if you need high precision. That's all I was saying
the overage would only matter over a very long time, and only if you care about very regular intervals
Yes, as I said
but yeah you can just go back to orginalValue - overage
It was just an interesting aside they may have wanted to know about
its good to mention depends on the use case
for spreaing some work out likely wont matter, but i could see it mattering for say a simloop for calculating states over a long time frame
though generally there you abstract thigns a little and start working with time slices
I use it for a moba doing waves, and for a rhythm-esque (not quite music) game
like a project i used to work on, would on startup compute what stats should be as if the game was always running
That's smart
yeah its not quite perfect, but more then close enough
not pefect since am not running the full NPC behaviors, but each one has on how long it normally takes and what stats to adjust. so the simloop can figure out which ones to execute and how things are effected for the time between the last save and now
How can I set this line:
"moveDirection = transform.forward * Input.GetAxisRaw("Vertical") + transform.right * Input.GetAxisRaw("Horizontal");"
to account for slopes, and project onto a plane that is parallel to the slope it is on, using normals?
ahoy lads. i'm messing around with dialogue, and i was wondering what might be a good method for managing events that can change options in either dialogue, or within the game, such as giving the player an item or unlocking a room. any suggestions on what i can look into?
Have you seen Ink before?
i've been directed towards it before with some of my first questions regarding dialogue, but i'm a little apprehensive about learning how to use another software as of now. plus, i want the challenge of learning how to make a system from scratch, so i'm trying to avoid it anyways.
ah, a masochist
exactly
wdym learning another software ?
its inside unity , the only thing to really learn is the markup and how it can trigger functions in your script
π€·
if you wanna do your own system then look at scriptable objects
or using json ?
Hey i have a question about tilemapping. In my TilemapManager script, I have this as a test:
private void Update()
{
Debug.Log(groundTilemap.cellBounds);
}
Which keeps spitting out
"
Position: (-17, -11, 0), Size: (29, 28, 1)
UnityEngine.Debug:Log (object)
TilemapManager:Update () (at Assets/Tilemap/TilemapManager.cs:35)
"
From the documentation, it appears like unity automatically resizes the tilemap depending on the size/contents you have painted in the tilemap. However, when i add more opjects to the tile map (ie expand the area), this debug message is not changing. What am I misunderstanding about the tilemaps?
I've also loaded another scene with a tilemap (which is smaller in terms of # of tiles painted) and it returns the same message
So scriptable objects don't appear to have a name field. Is it possible to do direct comparisons between SO's? Particularly, can I use an SO as a dictionary key?
They aren't game objects but other type of assets. What in particular are you trying to determine by comparing names?
This would basically be asking if you can use a class as a dictionary key, so yea should be fine π€
@lean sail I thought it might be something like that, I wasn't sure if there were some special comparison operators built into SO's.
are you referencing the correct tilemap?
i assume you havent seen much of anything else then
i have seen plenty
the tiles/tilemap can be better but its not that bad
Donno. In my opinion unity docs are pretty good. And I've been working with C#, C++, python, unreal engine and some other docs.
just wait till you try to use a new tool and the docs are quite literally just the existing method names and thats all.
just tested it and its accurate on mine
Yeah, I agree about the packages docs.
Which version are you on?
@dusk apex I have a mutable set of data per SO, Was just trying to think of a way to look it up without having to wrap those in another class and then use a string as a key.
me ? 2021 on this one but don't think version matters...the code is the same.
[SerializeField] private Tilemap tilemap; void Start() => Debug.Log(tilemap.cellBounds.size);
@rich leaf if you made the bounds big already and you see through code it doesn't shrink
you click the Tilemap 3 dots
After i clicked compress tilemap bounds, its only printing (0,0,1) now
I painted my tilemap using a game object brush, would that make any difference?
probably since they're not technically part of the tilemap
Whys that?
they're gameobjects not tiles
@rich leaf what exactly do you need it for ? you can probably place 2D invisible placeholders if you want matching size
Im confused on what the problem with this would be . Why are they not considred tiles if there is a built in brush for this in unity?
My long term goal is to serialize the tilemap data so i can save it to a file.
then you would save the gameobjects /type and their placements (pos,rot,scale)
Game is 3D using a 2D tilemap for the floor
its just an extra quirk / addon unity decided to add gameobject brush, it works with tilemap for the grid but its not part of the tilemap
its in the name GameObject brush not tile
Yes, but is there no way to utilize the tilemap to save these positions?
Like what was the point of them adding this brush capibility if it cant do that
to snap to grid 3D tiles with ease?
they're not tiles tho lol
like in the code
is each "tile" gameobject type an enum ? or scriptable object? just save wat it is and transforms.. then recreate it on load
So essentially just use the tilemap to paint the scene and thats it?
pretty much
nothing to special about tilemap unless you're using tiles it just saves you manually making grids through code
Could they not just use Tile.gameObject or am I misunderstanding
Does unity limit your fps?
I am literally only dispalying 1 sprite with a sprite renderer, the max fps (top left) is 3000?
shouldnt it be more?
Im trying to figure out a "clean" way to solve a bit of a puzzle, and Im not sure how to approach this.
I ideally would like an easy way to attach some form of variable/modifier to an instance of an AnimationClip, to indicate a specific frame, and specifically get "how much time does it take to get to that frame".
not a keyframe event mind you, this is info I need before I have even played the animation.
Effectively, I need some way to easily bake into a given animation reference that at a given keyframe, <thing> will happen.
In my case its for combat animations, I want to specify which keyframe is the "hit" keyframe, without having to play the animation and trigger with an event. This is because I am doing a whole bunch of logic way before the animation has actually played
Effectively speaking, I am going to need to synch up animations between 2 distinct entities that have their own animations, and I need to offset animation A so its "keyframe" will occur at the exact same time as animation B
So if AnimationA's keyframe is at 0.5s, and animation B's keyframe is at 0.6s, then I need to delay AnimationA from starting for 0.1s so they both hit their "mark" at the same time
you can use a stopwatch and measure the time?
I know the time but I ideally would like to do it by the frame, without having to keep jumping back and forth between animation <-> code, cause I have a lot of these animations and ideally if I could handle it within the animation reel itself thatd be better
Is there a way I can put some kind of "does nothing" marker on an animation, even just a special "does nothing" animation event keyframe, but instead of using it for firing off, I actually process the animation data and "fetch" the "timestamp" that event is set to
so essentially
when animation is playing...x seconds into animation play time...detect event...etc
no
I need to know this info before the animation is played at all
Im queuing up numerous animations that are gonna be playing out, and I need to keep them in synch dynamically
IE, player character swings sword animation, I have a "hit" keyframe on say, frame 7, enemy has a "I got hit" animation, but its actual "I got hit" frame is frame 3
I need the player's frame 7 to be happening at the same time as frame 3 of the enemy's animation
So I need to math out when to start each one before either of them have even played
I see
because in the above case, Id then go "Okay, I delay the enemy animation by 4 frames, got it" and then start
Is there a way to fetch the list of all animation events you have on an animation and parse their info and, specifically, get the exact time in seconds (float) that a given animation event is set to occur at?
cuz that seems like the easiest way to go about it
this might be of use
can you add event handlers to the animations and when the player takes action, an event (associated with player animation) is created and any registered animations just handle the event?
nah cause its dynamic
Im pre-queuing all these animations seperately "ahead of time"
create a script which on awake gets all the keyframes of said animation and their time and store it in a dictionary
you can then use said list to measure the time between key frames
Is there some kind of "does nothing" keyframe I can add to an animation?
Id need a property to add it to
Aight, looks like AnimationEvents are a lot easier to parse ngl, they even have the time value on em already mathed out, so I went with this for now
public static float AnimationHookTime(this AnimationClip clip)
{
foreach (var animationEvent in clip.events)
{
if (animationEvent.functionName == "AnimationHook")
{
return animationEvent.time;
}
}
return clip.length;
}
now I can just copy paste the animation event keyframe and it will "just work"
you can use a dictionary for faster look up time
instead of using strings use enums
enum for what?
"AnimationHook"
theres only one
oh ok
an animation will only ever have 1 hook
and its primarily just for "attacks", "taking damage", and "die" animations
pretty much animations that concern entity A interacting with entity B
where I actually need them to synch up so their 2 animations look right
are you creating a choregraphic video?
looks like you can register new events tho?
it's iterating over a collection of clip.events
uh sort of, turn based combat game where all the entities take their turn simultaneously
for sure but just normal events that do normal event things, this will be a specific "special" one I am abusing for this use case, the actual function doesnt do anything
its purely just a way to "tag" a specific frame in a super easy to parse way
but theres just this 1 type of tag atm
are you using dots?
So at the moment I have examples where like:
Player's turn is them attacking an enemy
Enemy's turn is "die to that attack"
I need to make sure the enemy's death animation, which will play at the same time as the players "swing their sword" animation, occur correctly and look right
nope, no idea what that is
Data Oriented Tech Stack
no because they are not Tile type and don't inherit TileBase
uhhh could be akin to that
eh
It's Jobs, ECS, and Burst compiler
you could speed it up by using linq queries too, return clip.events.First(x => x.functionName == "AnimationHook").time
ah, no, not using those yet
linq is slower
looks prettier tho
linq gets a bad rap
shouldnt have a huge impact because ideally I have this run in editor and becomes compiled in as a constant
Personally I love it, for simple things, rather write 1 lines than 5
cuz every animation is "locked in" at compile time, the times of those events are also "locked in" at compile time and are, for all intents and purposes, now constants
I have a general question
I don't have too much direction at work and I feel like I'm kinda stuck in a rut where I can get things to work with some googling, but my architecture is terrible
Are there any open source Unity projects or smth that I could look at/participate in so that I could see some possibly better thought out code?
Ive got a write up for my approach to my way I organize my project, you can feel free to try it out and if it feels good, its very easy to adapt and use
https://blog.technically.fun/post/unity/building-a-gamestate-with-zenject-in-unity/
Surely, there exists a game you fancy and wanna create it
I utilize a sort of MVVM approach to the codebase, where I have a game state that has a sort of Pub/Sub model to pushing changes to it, and then subscribing to be notified of changes, and then a service layer that holds 90% of my logic, and then monobehaviors purely have the job of being "glass box" code that each handle purely "what you see", basically they have all the "draw" logic for what is shown to the user.
im having vector math brain fart moment, what can i put here so the black fill is always aligned inside the LineRendered box(the scale is always right, but position isnt)
I really like it cause it keeps all my services decoupled and their only job is to either mutate the game state, and/or subscribe to game state changes and react to them
The site flickering hurts my eyes a little lol
most open source projects probably arent as readable as you would initially assume. It'd take you very long to actually learn from it. I think one example was unity's chop chop, but that was finished some time ago
I really gotta get around to adding a button to disable that ngl
I learned this the hard way, downloaded some assets from the store to learn from it. My god was that a pain
Maybe it'll be fun to look at
HAHAHAHAHAHAAHAHAHAHA
Or not?
I too tried looking at another project to see how I should do something, big mistake. It only demotivated me xd
just calculate the mid point of startPos and endPos if your fill is symmetric.
anywho @thorny spindle lemme know if you have any questions about my "PropertyWatcher" architecture, if you decide to try it out, I tried to design that little walkthrough to only take about 30 minutes to try out whilst introducing you to the core concepts of how it all works
I may at some point record a youtube video doing the same tutorial but in video form
ive been trying, but seems my math keeps getting off, im a lil tired ngl
I really don't want to seem rude, but trying to read the page was giving me a bit of a headache ^^;
There's also the gist here for the core code that is needed and examples in my comment at the bottom
https://gist.github.com/SteffenBlake/ace74a893d0b16c30a7eb2a42d6d9230
google middle of 2 points formula and you'll get what you want most likely
see, i was too tired to think of that xD ty
go sleep
no π
I was once so tired, I looked up,
How to tell if a number is negative
But since I did see dependency injection
Do constructors work with monobehaviours?
nah, you gotta do it via a different way with zenject
worst ive done is "How Vectors", so i know im not that tired yet xD
but I personally dont inject anything into my MonoBehaviors
Oh, so that's why you said the asset was needed
Then where do you use it? Just classes that act in the background that your monobehaviours reference?
nah thats something else, the .cs file is all the PropertyWatcherBase stuff which you use for building the "Game State" layer, basically it does all the hard work for you of setting up the whole Pub/Sub model
Oh tonnes, but my main rule is I always have my MonoBehaviors at the very "bottom" of the tree.
I inject the monobehaviors into my services, but they are the "leafs" of my DI tree
basically, my services "own" the monobehaviors and will do stuff with them, the monobehaviors sit at the very very bottom, nothing gets injected into them
I have a pic here somewhere, one sec
Ah, so the monobehaviours are the last step that gets put in. But won't you have times when you have to initialize monobehaviours with some parameters?
indeed, but the service is in charge of that and it keeps track of any entities it has created and it has all the CRUD methods on it
its sort of like MVVM:
GameState's backing model: Model
GameState: ViewModel
Services: Service/Business Layer (not directly mentioned for MVVM but typically used)
MonoBehaviors (aka Entities): Views
I dont include the "model" in the pic cause thats sort of varied by implementation. It could be a database, could be a file, thats up to you
I guess itd sorta look like this
So you have a thing that maintains the top level game states (GameState). Then a layers right below it that manages specific aspects of the game (Service layer). Which then creates/destroys GameObjects (Entity Service)? That have all the general riggings of the Monobehaviour(transform, rigidbody, etc). That notify changes to the Gamestate?
Pretty much yup
The Entity service then either talks directly to the Service Layer or the GameState layer as needed?
In practice I havent yet had the Entity service actually talk to the GameState, I could but I havent had to. The Entity Service is just another service, I just singled it out cause its the special service that is how all the other services can actually get references to a given entity
But wouldn't scripts in the Service Layer also end up being MonoBehaviours if you end up needing them in the scene with editable fields?
Services should be stateless and immutable, they purely are a bunch of "Does a thing" methods on a class
if you wanna have a configuration mechanism, you'd have a seperate class that holds your configuration (which can be a MB if you want it to be editor editable), and then you can inject the config into a service and read values off it
I'd really like to see a project where you've implemented this lol
I feel like that'd be the fastest way to understand
So in a weird way you'd be using the MB class as a holder of values that you then inject into the service when you instantiate
So you could probably just get away with a Scriptable for that or smth
yup
personally I prefer to store my configuration in JSON though, but thats just me being a web dev
Ahah
largely speaking though I dont really "configure" the services since its a video game, you dont really... configure a game once its compiled and launched
Well I need to work with artist in the company so it'd be nice for them to be able to drag/drop and edit values on the fly the inspector too
what would be an example?
I guuueesss you could do it with scriptables and addressables if you wanted to configure after launch
I do have 1 special "debug" monobehavior I made explicitly for manually manipulating (and seeing) the GameState at runtime I will note
Just what prefabs to instantiate etc
and its setup to not be included in a publish compilation, debug only
Do you have an open project where you've used this kinda configuration?
I'd love to take a gander
I dont atm no, sorry D:
D:
The lesson was nice though. It's made me think a bit
there's a link to it at the bottom of the guide, one sec
Would looking at it give me a better idea of how you're using that system?
Sort of, its very bare bones since the services are simple and dont really have dependencies
I'll def take a look at it when I get off work then
https://repo.technically.fun/sblake/INotifyPropertyChangedExample/src/main/Assets/Scripts/Services/EntityService.cs
This one demos a bare bones basic entity service. Entities are injected in, it handles mutating them and "bubbling up" their events to the game state in a meaningful manner
Note how the ButtonEntity has no contextual understanding of what its "click" event does on its own, the EntityService handles translating that click into actual impact on the game state
And the TextEntity just has a SetText method, it has no concept of what its text is, its just a string and it doesnt care what string is passed into it. It has no conceptual understanding of the game states "counter"
How do you decide what goes in the GameState vs What's in the Service Layer? I'm guessing the Entity service is just whatever the gameobject needs to function
GameState is just a whole buncha properties that hold the data
But what data is GameState 'worthy
GameState "is a", it doesnt do stuff, it "is" stuff
Services "does a", they are immutable, hold no data themselves, and just "do" things
Ahah
Everything more than 1 entity needs to access largely
So the service is literally a bunch of methods that 'do', and all actual numbers are held by the GameState?
exactly yup
Seems a little top heavy
Seperation of Concerns ftw β€οΈ
!learn
π§βπ« 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/
The monobehaviors can be quite large if they have many things to "render"
Largely speaking the monobehaviors domain is the stuff you can "see"
wth this website isn't loading even on a good wifi connection ;-;
Stuff like a button and text are very simple cuz you typically dont mutate a lot about em (like aside from the text's string itself, mayeb you what, modify if its bold/not, its color maybe? Not a lot you typically modify), but my Player's character entity is about 300+ lines of code long, because theres a LOT of logic for what it visually is doing/looking like
- Translations of its transform
- Direction they are facing
- Animator State
- Collidor events
- Queuing animations (this is the majority of it though)
- Triggers for playing sound effects
Okay. So I have to kinda just make decisions on what data is a 'GameState' and what is 'LocalState' on the fly then
And make the services in the middle methods to go back and forth from these
Largely speaking your LocalState stuff is:
- Not something you need to serialize and save in your game saves
- Something that only matters to that one entity and others dont need to know about
but yeah you sorta just get the feel for it, usually if you put it on local state and then go "ah dang, I actually need other entities to know this stuff" you then bump it up to the game state
But what if you wanted to save the location and state (HP, attack state, animation state) of every npc in your scene?
Feels like there could be a world where nearly every LocalState is part of the GameState
could be yup
Keep in mind that the game state is the like, non abstract version of the data
Like for your HP
Game State: HP is an integer value
Player health bar: HP is its width of the red box in the bar, and the text displayed
So your monobehaviors "local state" are usually more abstract representations of the "real" values
I see. So technically the 'int _health' in this case would the the most base info. Then you would probably have the entity(GameObject) do something else with that data anyway
Like for example, my "character state" is an enum in the game state. The monobehavior however is like, what animation is playing
precisely yup!
Thats where the services come in, their job is typically to translate that "raw" data into something that the entity can actually work with... if needed
Currently I'm doing something like having a master 'manager' class that then has a bunch of 'lesser manager' classes that take care of stuff
But the difference here is that the lesser managers are pretty tightly coupled to objects in the scene
Like I'd have a UIManager that I just drag/drop UI elements into its inspector
How would I break this type of coupling in this case? It feels like it'd be hard
Like for your HP bar, you'd have perhaps
GameState.HP
GameState.MaxHP
And then the service turns it into
float hpPercent = (float)GameState.HP / GameState.MaxHP;
string hpText = $"{GameState.HP}/{GameState.MaxHP}";
HPBarEntity.SetHP(hpPercent, hpText);
nothing wrong with your PlayerManager being coupled to the PlayerEntity, that makes sense
its okay if your FooService is coupled to your Foos
But I mean if you want something like your UIManager to ONLY be a bunch of methods
for Zenject you'd move those serialized fields over to your Registration monobehavior and register em there
Wouldn't it be better to pull what UI to activate/deactivate not be in its inspector
Since the model seems to say that the UIManager shouldn't be a MonoBehaviour?
indeed yeah
Does it just get injected into it?
You just move where you "register" your monobehaviors is all
handily, the thingy you use for Zenject is already a monobehavior you can add serialized fields to
But then that would mean that I would just have a ton of scriptables that are referenced by the GameState that then inject these into the lesser managers
So Startup is my Zenject registration spot (called a MonoInstaller)
lol assuming I don't use Zenject
oh you really do wanna use a DI engine of some sort, manually doing DI by hand is uh... a huge pain
I have like one service stack that is like 6 layers deep
lol the projects at this company is pretty small deals for now
like 1~2 month art projects
I would never wanna have to manually do like
new ServiceA(new ServiceB(new ServiceC(new ServiceD(new ServiceE(new ServiceF())))));
So I think it shouldn't be too bad / would be a fun way to be in pain
This for example is what my entity service just looks like
[Inject]
public EntityService(GameState gameState, List<EntityBase> prefabs, List<IEntity> entities)
{
GameState = gameState;
Prefabs = prefabs.ToDictionary(p => p.GetType(), p => p);
foreach (var entity in entities)
{
Watch(entity);
}
Entities = entities.ToDictionary(p => p.Id, p => p);
}
Well how I'd do it is that I'd have scriptables on scriptables on scriptables....
Scriptables would be MonoBehaviors, I wouldnt inject a scriptable into a scriptable :p
or whatever their shared parent is
I see what you mean
but nah zenject is pretty easy to stand up
My way of doing it would be pretty dumb lol
Its like, 4 steps and staples in pretty quick
I was going to set up the scriptable pyramid by hand
then inject it layer by layer lol
yeah zenject's whole deal is it handles that for you, highly recommend it
works with IL2CPP too β€οΈ
oooh
lol
I'll do it by hand first
And then look into it maybe
Or give up in the middle and use it straight away
I will note if my blog's post is too difficult to read, you should be able to just Ctrl A + Ctrl C + Ctrl V it into like, google docs to make it more readable
Sorry I've fallen in the hole of depending on assets and then having to tear it apart layer by layer to recreate it due to problems in the past
if you go through that guide, it's fairly easy to bootstrap up
I'm also massively depending on AutoHand for my VR stuff, but I'm planning on trying to recreate a bare-bones version of it by myself soon-ish
Im not familiar I must say
But thanks! π
This gave me tons to think about!
Was hugely helpful
I actually saved your diagram lol
lmk if there's anything I can do to help
Looks like a very web-servicey way of approaching Unity lol
the gist is open to pull requests if you ever spot any fixes/improvements/optimizations, and can always comment on it and I think I'll get a notification about the comment?
or you know, can just ping me on here about it
the gun is not using the correct ammo type
if I fire my Assault Rifle (AR ammo), it fires Buckshot. if I fire my Shotgun, it fires Rocket. how do I fix this?
https://hatebin.com/ozuuvpjlwq GunCore
https://hatebin.com/meqmfzkfba AmmoMaster
@rancid frost @devout belfry keyframe worked, animations feel a lot smoother now (before the snakes would "die" as soon as the sword swing started, instead of when the swing "connects"
Vid of it working: #archived-works-in-progress message
Thanks for the help!
what part actually handles instantiating bullets? all i see is
int shotsFired = ammo.Spend(ammom, ammoPerShot);
if ammom is the value you expect it to be then the issue is with firing
Wheel[] wheels = GetComponentsInChildren<Wheel>();
wheelInfos = new WheelInfo[wheels.Length];
for (int i = 0; i < wheelInfos.Length; i++) wheelInfos[i] = new WheelInfo() { wheel = wheels[i].transform };
if can it be shortened with LINQ, how?
do you really need to use linq for this? its fine as is
GetComponentsInChildren<Wheel>().Select(w => new WheelInfo { wheel = w.transform }).ToArray(); ?
thanks thats so much shorter
can make a static function too to shorten it more
.Select(WheelInfo.FromWheel) :3
now you've got a FromWheel static function too
public static WheelInfo FromWheel(Wheel w) { ... }
I havent tried it but I wonder if contructors can be implicit cast to Expression<Func<...> for Linq...
Doubt it but I don't care to elaborate further on what was a fine answer
like can you just do
.Select(new WheelInfo)
if your constructor was just
public WheelInfo(Wheel wheel)
hmm
looks like... no you cant D:
Since LoadAllAssetsAtPath doesn't guarantee the order of items according to the documentation...
https://hatebin.com/nmsoaoqrow GunShoot
I have not touched this code since way before it malfunctioned so i think this code is fine
https://hatebin.com/ttuyuesyqu AmmoInv
This stores the Spend function, maybe this has the problem?
the first thing you should really do is add debugs. You have some debugs so add onto those because right now they arent printing anything useful for you, see what values your ammo types are. I really cant suggest anything else,
1 because i dont want to go through all this code to debug your code in my head and
2 because I cant see what values most of these things are
Hey does anyone know if I am able to use a Unity CCD bucket to hold non addressable related files? I want to use one to hold a screenshot and a txt file and then pull those at runtime
I'm using a cinemachine POV camera for the vertical mouselook and rotating the gameobject for horizontal, however I'm getting this stuttering / stepping effect when turning. It's especially noticeable when moving and turning at the same time. Any help please?
change update mode to fixed
and/or make sure camera is not parented to the controller
The virtual camera?
i havent worked with cinemachine, but if the camera follows the virtual camera, yes
hi guys what is the diffrence between this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BuildingSystem : MonoBehaviour
{
public class BuildObject
{
//code here
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BuildingSystem : MonoBehaviour
{
}
public class BuildObject
{
//code here
}
one is valid c# another isnt
sorry its class
there are plenty of differences
nested class has access to all private members of the parent class
nested class accessible through parent class name
thats about it lol
Consider using the 2nd version if BuildObject is used outside of BuildingSystem.
yea is is used outside
yeah , once you have anything serialized as that nested class it will be hard to move it out
oh ok thank you guys
You're a genius...
Although it has broken my horizontal mouse look, I'll fix that. Thank you π
it happens because it being parented to an object that moves in the fixed update loop prevents it from being interpolated correctly in normal update loop
in most cases you dont want camera attached to an object
Is it possible to make a dashed line using the Line Renderer component?
Not a code question, but yes, using a dashed line material and setting the render mode to Repeat
Hi! I'm getting an error with dependencies. Can I post the log here?
I'm having an issue with the cinemachine camera following the yaw of my player. My player is definitely rotating, parented to the player is an emtpy called "Eyes". I've tried setting my virtual camera to try using the player as the body, but it doesn't take the rotation of that either. BTW, I intentionally set the horizontal speed to 0 so that there's no horizontal rotation from the camera.
sorry for the wall of text this is the error on my console
An error occurred while resolving packages:
Project has invalid dependencies:
com.unity.feature.2d: Package [com.unity.feature.2d@1.0.0] cannot be found
Package com.unity.feature.2d@1.0.0 has invalid dependencies or related test packages:
com.unity.2d.animation (dependency): Version 'default' is invalid. Expected a 'SemVer' compatible value.
com.unity.2d.pixel-perfect (dependency): Version 'default' is invalid. Expected a 'SemVer' compatible value.
com.unity.2d.psdimporter (dependency): Version 'default' is invalid. Expected a 'SemVer' compatible value.
com.unity.2d.sprite (dependency): Version 'default' is invalid. Expected a 'SemVer' compatible value.
com.unity.2d.spriteshape (dependency): Version 'default' is invalid. Expected a 'SemVer' compatible value.
com.unity.2d.tilemap (dependency): Version 'default' is invalid. Expected a 'SemVer' compatible value.
com.unity.2d.tilemap.extras (dependency): Version 'default' is invalid. Expected a 'SemVer' compatible value.
do not hesitate to dm/ping me if you can help! ill greatly appreciate it!
resolved, i went to package manager and removed a package that had an error
did you open a project in new unity version?
no, 2020.3.5f1
new relative to the project
no
so new project and manifest was already broken?
yes, i just imported the roguelike package and it was automatically broken
wonder what can prevent pm from pulling deps like that
oh
so i was right
it is a project
i am sorry, i might have misunderstood your question. It does say i can use 5.x so i assumed it was not new to the project
it is indeed a project from the package manager
anyway, Version 'default' is invalid. Expected a 'SemVer' compatible value this means at some point they changed some syntax/token naming in their dependencies xml/manifest
so package has old or incompatible xml structure so pm fails to resolve deps
yeah i found that and removed the package that was making the error
and everything works now!
i asked over on #archived-machine-learning but ill post it here if it isnt a problem, it is code related i believe
I'm looking forward to implementing MLAgents to https://learn.unity.com/tutorial/unit-mechanics?uv=5.x&projectId=5c514a00edbc2a0020694718. Do you think it's feesible to do that in 1 week time? I don't need it to be too advanced, just usable!
Hey guys, looking for a name of this type of variable storage with this function (dotween is slightly irrelevant in this case)
s.Insert(0, DOTween.To(() => particleMoveSpeed, x => particleMoveSpeed = x, standardParticleMoveSpeed, transitionSpeed));
I'm lerping the particleMoveSpeed to 'standardParticleMoveSpeed'
if this is just a 'lamba lerp' then thanks for being my rubber duck everybody but if this also has a more specific name I would really appreciate some pointers
yes its lambda, first one is a Func<T> getter, second is Action<T> setter, or whatever delegate types is has declared
the overall term for it is delegate
Thank you!
No I have tried that but wondered if it could be done in code. Which material type would you recommend?
The one that's supported by line renderers. It's the image you put into it that has the dotted pattern
Search for t: AudioSource in the search bar of the Hierarchy tab
ah thanks
hmm thats interesting
i guess i aint got any audiosource
How u know you have an audio source than?
idk i just thought i had one, but i guess i dont xd
i will add some tho
hmmm can i listen to music?
can i listen to ingame sounds if im simulating a phone?
doesnt look like its got any sound
Ask in #π»βunity-talk or #π±βmobile as it's not a code question
Oh my bad forgot the channel
How do I get a gameobject to stay inside the boundery of a collider/colliders?
How do I send large code snippits in disciord? I know there is some app and I need to if I want osme help on this issue.
!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.
thx
Wait just solved the issue, I've spent hours on it but litterily just solved it.
actually I've still got a few unresolved issues.
So this is the code for my hardcoded 2D character controller so far. I had to stop with some other aspects because the collisions aren't too good. Firstly, running into a wall when on the ground will have an affect of glitching in and out the wall repetitively, and I have no idea how to fix it. Secondly, because you go fastest when in the first half of your jump, you have enough momentum to properly glitch into the wall, despite the fact that my raycasts system is checking 5 tiles to the opposite direction of he wall to find a safe place to teleport too. I have more concern for the second issue as I think maybe making a raycasts to test weather a wall is nearby and then teleporting the distance of Xvelocity minus distance to the wall in the last frame would resolve the first issue.
Oof, I just showed you how to post code and then you do it this way that doesn't work on phones and has no colors
second idea might work really well actually leme give it a try
Anyhow, given your text description, usually people don't use the physics methods for physics objects, and translate the physics object into the into the wall and then the physics engine corrects it back again.
This will give you the jittery movement.
yeah If i do XVelocity minus the distance to the wall in the last frame * -1 if itsd oging to the right then it will correct it in 1 frame i think
If you just move with the physics methods you wont have this problem at all.
Yeah but I don't want to be constantly fighting a rigidbody I want to have control over my character
Also I have programmed parabolic jumps and falling while being able to plug it into desmos and see my jump curve, which I don't think is tooe asy to do with a rigidbody
Yeah this is easier to code, more peformance efficient and cleaner to run.
Hello, I want to make a simple foldout attribute but Idk why I get an error
[CustomPropertyDrawer(typeof(EventFoldoutAttribute))]
public class EventFoldoutPropertyDrawer : PropertyDrawer
{
bool showPosition = true;
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
showPosition = EditorGUILayout.Foldout(showPosition, property.name);
if (!showPosition)
return 0f;
return base.GetPropertyHeight(property, label);
}
}
What's wrong with my code?
error:
ArgumentException: Getting control 1's position in a group with only 1 controls when doing repaint
Does this look applicable: https://stackoverflow.com/questions/73846693/argumentexception-getting-control-1s-position-in-a-group-with-only-1-controls