#archived-code-general
1 messages · Page 433 of 1
Free Project file: https://www.patreon.com/posts/unity-tutorial-98269459
Patreon: https://www.patreon.com/SleepyLava
PC/Web games: https://sleepy-lava.itch.io/
Android games: https://play.google.com/store/apps/dev?id=4712677237821359521&hl
Like and Subscribe.
#unity #gamedev #unitytutorials #unity3d #unitygameengine #unitytutorial #unitytu...
What function do you usually use for rotation during/according to movement, Euler or another?
depends what's being moved and how
I've set up movement for a player object but I also want it to rotate in the direction it is moving.
yes, but you can make things move in different ways.. mainly via physics or not
Also is it 2D or 3D
this is also a #💻┃code-beginner topic
simplest rotation movement transform.forward = move;
Yeah, forgot to say it's 3D (first project) and I'm using Rigidbody
Thanks, I'll try MoveRotation, I had been using just Move for the rigidbody
oh ya forgot Rigidbody.Move also exists, never used it but seems this also lets you rotate ?
Quaternion targetRotation = Quaternion.LookRotation(movementDirection);
(only do this if you have moveDirection inputs otherwise you get an error setting rotation to 0)
yeah, Move also seems to rotate
Wdym?
but not in the correct direction, like in the opposite direction
Pretty sure that rb.MovePosition/MoveRotation are meant for kinematic rigidbodies
iirc MovePosition is
Not sure if they detect collisions properly for non-kinematic ones
Move seems to be different
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Rigidbody.Move.html
never used it tho
I assume Move to just do MovePosition + MoveRotation
Why do none of those docs say anything about collision detection
Like does it respect collisions or no
I think it should as long its not kinematic i suppose
MoveRotation only mentions interpolation 🥹
best thing is for op to 
Does anyone happen to know why you cant assembly assembly like inventory -> item -> guid because you cant reference GUID in Inventory?
"cant assembly assembly" ?
can you explain a bit more 😅
i meant like you have to reference the GUID assembly in every single assembly you want it to be used in, rather then having the assembly already having access to it due to already having access to something that uses it.
if you try to use GUID in inventory with this reference path you get "Could not find definition for GUID"
if Inventory depends on item, and item depends on guid, shouldnt by transitive property, inventory depends on guid
ahh assembly definition files?
yeah, for seperating code
so do you need to add explicitly GUID assembly to Inventory ?
I've only used asmdef for some assets
yes, for it to work right now. feels like im having to reference like for item interaction, Item interaction -> GUID, Item -> GUID
isn't that normal ?
I mean i would think that if i tell it hey, reference the item class, that means it should also reference the SerializableGUID, because thats what item references
but it doesnt work that way, i need to have 2 assembly references, GUID, and Item
like inheritance ?
yes
oh no idea I would assume would not be good the way asmdef are designed to be modular
It would have loads of bloated dependencies
unity docs show this picture as a reference, but its really confusing
yeah one references only what it needs
yeah, but my interpretation is that main could see Library.dll, just that Stuff cannot see Main or Thirdparty, and library cant see any of it
I suppose its no reason library should know about thirdparty and main
The reason i need it this way is that ALL my systems use GUID as a way to seperate A. Items, and B. Player instances.
Yeah, that's correct. In this case, Library.dll would not need to run any code from Main.dll, which would make sense if it were a library
Netwonsoft doesn't give two shits what my game does
it just exists and I use it
Yes, but in this case, why can Main.dll not see Library.dll?
because main isnt using it
suppose you delete Stuff., we no longer use this code, now main has to error too for what reason
Well, if Main had a dependency on Library, you'd need another arrow. In this case, Main uses Stuff which uses Library. The point is that each assembly only cares about the things it, specifically, uses
This way, if you were maintaining Main, you wouldn't care what libraries Stuff uses, as long as Stuff has those dependencies properly set, all you'd need to do is add the dependency to Stuff
Ahhh, ok modular code is the main purpose, i was thinking about it more so for how unity recompiles things. thank you for the explaination digi, and thanks for the help nav
It's mostly for modular code, but it does end up leading to some speed up. For example, if ThirdParty.dll changed, it wouldn't require Stuff.dll to recompile
yup one main stink about having everything in CSharp-Assembly
change 1 line, ALL scripts recompile
yeah, i ran into using assemblys to help speed up editor compile times, as quicksaving scripts hurt me, even for a small number of scripts
(also remember to try to code around disabling domain reload)
the benefit of speedy recompiles and modular libraries, at cost of having to compartmentalize everything
this helps only going into play
but thats huge
should've been default lol
I feel like its a safety net, to ensure that no matter what the person codes, that their game plays in editor according to what it would be ingame.
better to annoy the people that have to change it, then to deal with the people who bring issues that are only due to domain reload being disabled
yea true, cause of statics not resetting state and all that
yeah, tho for statics that are just databases, not resetting state actually helps XD
gone are those days lol now its either SOs if I dont mind reset beginning exe or file for permanent
Has anyone come up with a better world partitioning than chunks for games with large terrains and structures that span several chunks?
Cause it just feels messy
Sure you can calculate how many chunks a structure occupies during generation and generate all of them or defer the changes
And make chunks dependency so that the entire structure is loaded\unloaded but I can't help but wonder if there's just a better partitioning for this kind of game
Is it normal that when I try to use the new InputSystem like this, it makes my game lag / my mouse sensitivity and movements are to slow ?
._.
It gives me this, so I guess it's the solution however I don't know where to disable it ?
In OnDisable() ? OnDestroy() ? Or somewhere else ?
You should probably not use System.Numerics in a Unity project
Unity's got their own versions of numbers for a reason
These errors are coming from scripts in an asset called SQL for Unity Database
seems like they're intentionally avoiding UnityEngine in some scripts
yeah without editing any of the files, this is what it spits at me when I try to compile
Seems like a problem with whatever that asset is
Maybe an assembly definition is missing something?
Are you using Rider or a Jetbrains software ?
I'm not sure what either of those are ngl
Code Editors / Ides
I use visual studio .-.
Oh ok, but I think the answer to your problem is still the same which is this #archived-code-general message
how do I avoid that when the code is from SQL4Unity?
I don't know what that is but usually it has to do with a setting related to suggestions and I guess when you typed Vector3 it suggested you multiple Vector3 from different library / namespace and the first one is System.Numerics and you accepted that one instead of the one made by Unity.
I should clarify maybe
this is what the asset gives me by default
this was from my attempts at fixing it by editing the asset directly
which I'm kinda hesitant to do because this asset is for doing SQL database queries in any version of unity
which sounds like something that shouldn't be messed with lol
Im trying out assemblies for the first time to try and get compile times down and maybe I'm doing it wrong but to test it out I made a folder with only one monobehaviour script in it and the assembly definition and it is still taking 30+ seconds to compile.
Then perhaps code compilation is not your problem. It shouldn't take 30 seconds anyway.
Compilation is usually the faster thing during assembly reload.
interesting
The asset might not work with whatever version of unity you're using, or it might require additional setup steps
Check the editor log to see what unity is doing and what's taking time.
ah, I guess it does say it's for 2019.4.40f1, I'm using Unity 6
okay I found this line "Asset Pipeline Refresh (id=36ad307957243004a937f00f34473b93): Total: 34.632 seconds"
is this just a cope moment
No. Assets shouldn't take 30 sec to refresh either. Unless you're actively modifying some assets every time.
no sir i am not
Check the log for more clues. If there's none, maybe using the profiler could help.🤔
Also, try undocking/closing any extra tabs in the editor if you have any.
sounds good i’ll get back to you 🫡
Hi everyone!
I’m working on a Unity project where I need to perform a Raycast, but I want it to only check for intersections with one specific Collider and ignore all others (with same layer). Essentially, I want to know if a Ray intersects a particular Collider without checking against every Collider in the scene.
Thanks!
Use Collider.Raycast
that's exactly what it's for
Sorry. I have collider2d. forgot to say
ok then Collider2D.Raycast
Its not the same( works differently(
Oh lord why does that work exactly opposite lmao.
One thing you could do is temporarily move the single collider to a specific z coordinate that nothing else is at and use a contact filter with https://docs.unity3d.com/ScriptReference/ContactFilter2D.SetDepth.html
Thanks
Anyone know why the x axis is continous, but the y isn't?
public class Chunk : MonoBehaviour
{
private float NoiseHeight(float worldX, float worldY, int seed, float scale, int heightMultiplier)
{
float xCoord = worldX * scale + seed;
float yCoord = worldY * scale + seed;
// Generate Perlin noise value (between 0 and 1)
float noiseValue = Mathf.PerlinNoise(xCoord, yCoord);
// Center around 0 and apply height multiplier
return (noiseValue - 0.5f) * 2 * heightMultiplier;
}
private void GenerateVertices(int x, int y)
{
int chunkX = (int)transform.position.x;
int chunkY = (int)transform.position.y;
float scale = 0.01f;
int seed = 0;
int heightMultiplier = 75;
for (int i = 0, xi = 0; xi <= x; xi++)
{
for (int yi = 0; yi <= y; yi++, i++)
{
// float height = heightMap[xi, yi]; // Get height from the heightmap
_vertices[i] = new Vector3(xi, NoiseHeight(xi + chunkX, yi + chunkY, seed, scale, heightMultiplier), yi);
// _vertices[i] = new Vector3(xi, 0, yi);
}
}
}
}
Are you intentially always assigning _vertices[i] and never incrementing i?
oh wait I see where i is incremented
yeah I should probably change that to make it more readable
So you're asking about the holes?
It's almost as if the rows are exact clones of themselves.
The x is perfectly continuous, but the y isn't.
Yeah that cloning part is happning because you're sampling Mathf.PerlinNoise at integer intervals
I think
Yeah there are a lot of duplicate xCoord and yCoords
So it's somehow just generating the same row a bunch of times.
Turns out I am the dumbest guy. I was using the chunks height in the world (always 1) to determine it's y position (y as in y on a 2d plane).
How to I invoke a method only when the left mouse button is clicked, and only when it clicks anywhere on the screen except a UI button? Right now, I have an OnClick() event that shoots the gun, but the gun still shoots even if it was a UI button that was clicked.
Have a UI manager that checks if the pointer is overlapping any ui. Then wherever your shooting logic is, ask the UI manager wether the pointer is over ui or not.
So there's no built-in way to do it?
Seems like a design oversight
No, because this is a very project specific feature.
Really??? It seems like almost every 2D game would need it
There might be cases where you want to click through the UI. And it's not even clear what you want to consider ui or not. Too many factors to consider that prevent making it a standard feature.
Is there an easy way to get if the mouse is over a button
What about 3d games then?
I mean I imagine every 3D mobile game would need a way to detect clicks on the screen but not on a button
There should be callbacks on the button for different states, including hovering or pressing. You could also make use of the graphic raycaster.
Well, unity is not just for mobile games.
Because Unity is for all types of games, it should have features for all types of projects.
That's impossible
I feel like what I'm asking for is an extremely basic feature though
I know how to get around it being missing of course, but I just didn't expect it to actually be missing
It's not. But there are tools in unity to do that. It's just that you need to write some code to make use of it. As I mentioned in the first message.
I can easily imagine a scenario, where there's an invisible or maybe even visible full screen panel on the canvas. If that feature you're asking for was in the engine, it would always consider the pointer over ui.
There's just to many factors.
Besides, you would usually have a sort of UI manager in any project.
I also don't think there are many engines with that feature.
Maybe some very specific narrow engines have.
This would return true on non ui objects too if physics raycaster is used afaik.
I'm having a weird behaviour I honestly don't understand:
I'm trying to create a Runtime Set (List in scriptable object): https://pastebin.com/MUcRbm1H
and whenever I add something to it I get a mismatched type:
Concrete set: https://pastebin.com/LryUS9Dw
Set user: https://pastebin.com/M4sqJjy4
The thing is this is basically the code from 2017's Austin Talk: https://github.com/roboryantron/Unite2017/tree/master/Assets/Code/Sets
EDIT: Fixed wrong link
So the list should get filled when the game object is enabled, and this does happen, however:
Did you try assigning it by hand?
Indeed if I open the project from the 2017 talk I noticed I still have the same behaviour. I'd like to know why this is happening though. It's easy, you get a list and an element subscribes to it:
I did, it looks like for some reason it's only accepting assets and not runtime game objects
assets can't contain references to gameobjects outside their scope
Runtime objects?
Just game objects
Runtime scriptable objects??
The script you shared inherits from SO though..?
you could put prefabs in a scriptableobject but you can't put objects from a scene in them (atleast in the context of the scriptableobject as an asset)
Thing.cs inherits from MonoBehaviour, I was trying to insert an object living in the scene inside the runtime set
So the whole concept of Runtime Sets that they talk about here is just a lie?
That's not possible and never was possible.
Probably misunderstood the concept.
Let's have a look
https://github.com/roboryantron/Unite2017/tree/master/Assets/Code/Sets
Here's the code for it
using System.Collections.Generic;
using UnityEngine;
namespace RoboRyanTron.Unite2017.Sets
{
public abstract class RuntimeSet<T> : ScriptableObject
{
public List<T> Items = new List<T>();
public void Add(T thing)
{
if (!Items.Contains(thing))
Items.Add(thing);
}
public void Remove(T thing)
{
if (Items.Contains(thing))
Items.Remove(thing);
}
}
}
using UnityEngine;
namespace RoboRyanTron.Unite2017.Sets
{
[CreateAssetMenu]
public class ThingRuntimeSet : RuntimeSet<Thing>
{}
}
using UnityEngine;
namespace RoboRyanTron.Unite2017.Sets
{
public class Thing : MonoBehaviour
{
public ThingRuntimeSet RuntimeSet;
private void OnEnable()
{
RuntimeSet.Add(this);
}
private void OnDisable()
{
RuntimeSet.Remove(this);
}
}
}
afaik you can do this but it's not going to show up in the inspector nicely nor be preserved in any good way outside of play mode
If it's only a serialization thing, whatever, I clear the list every scene load anyways so it's not a huge issue... I'd like to understand if idk maybe I'm misunderstanding something
dlich can correct me if im wrong but i believe that's the case
It feels weird that a talk posted on the unity yt and considered the base for SOAP architecture is doing something wrong
(hence why as far as i can see he doesn't actually preview the so during the play mode test)
Indeed, that's only gonna work at runtime.
It's not entirely wrong. It's wrong to assume that the references are gonna be serialized.
quick jank solution is just to hide that list and have a list of string values or something and add/remove the objects name during your add and remove function
Enabling debug inspector might show the items assigned. Not 100% sure.
Oh this is probably a faster idea, yeah
If you want to serialize references to scene, then Unity doesn't support that. I suppose you could store it as a pair of scene ID and script's ID, then during initialization check if the ids match. If you don't want to have it serialized, then add NonSerialized attribute to the Items list - it will no longer be visible in inspector and serialized, but it will work in the runtime.
I don't have the money for SOAP so I'm trying to build my SOAP library 😅
And trying to learn something new along the way
knowing is growing 🌈
Yeah so I will add NonSerialized to the list and draw a list of strings, thank you!
With NonSerialized attribute even normal references should work. At least it worked for me when I tested it out.
private void OnEnable()
{
RuntimeSet.Add(this);
Debug.Log(RuntimeSet.Items[0]);
}
Thanks <3
Can I make this list serialized so that it shows up but the contents not editable from the inspector?
The workaround I'm thinking about is OnValidate, make sure that everything is in sync
but maybe there's a decorator or keyword for it
The package NaughtyAttributes has a feature that allows it:
https://dbrizov.github.io/na-docs/attributes/meta_attributes/read_only.html
@whole sorrel Btw, have you considered moving this from ScriptableObject to some sort of GameManager? ScriptableObjects are made mostly with persistent data in mind. They can be used to also store runtime data, but it might create some unexpected confusions (like the one where you tried to serialize a reference to a component inside of a scene).
(they are doing this because Unity offically suggested it)
Yeah that and also generally Game Managers are generally singletons and I've had times where I had to import three different systems to debug only one
probably my design issue, I'm still learning
but I want to test out SOAP and see where it leads me, pros and drawbacks
Is there any specific reason why VS Code is not finding the namespace even though the package is installed?
wtf Visual Studio
Oh it doesn't have an assembly definition...
I think using ScriptableObjects for runtime data could be handy for save data if someone wants to be able create asset presets and possibility of creating save files in runtime, that way both features could share the code.
https://openupm.com/packages/com.dbrizov.naughtyattributes/ did you install the package?
I installed it via git link but it doesn't have an assembly definition and if I install it via the package manager it imports everything in my assets folder
You'll have to reload VS after the package is added
I think Git likes to extract packages to the assets folder
No
Follow the manual install instructions that UPM has
This puts it on the packages folder
does it not? mb
NaughtyAttributes repo has their stuff in the Assets folder
ah, that's why it ends up in the asset folder then
I think their might be weird issues with editor stuff being in packages but used in assets but i could be mistaken
I'm not looking at my project ATM, but I could have sworn that package went into my packages folder
That's exatly what I did, if I install via get it gets put in packages but I can't reference to the namespace since it doesn't have an assembly definition
huh, try restarting VS maybe
I directly changed to rider lol
I've wanted to do it for a while
Even rider can't detect it
Weeeiird
oh wait it does have an asmdef
For future reference, scripts in packages require asmdefs
Is it possible that my issue is because my scripts are in a package itself?
dunno, maybe I need to add something to the package.json?
Because I can reach the namespace from my asset folder
Did you reference the assembly from yours?
Aherm...
Do I need to?
(first time making a package)
Yes
that was it
thanks
But I wonder, how do I add it as dependency since for what I've seen the unity docs want package names as deps, not git urls
Alright, thanks
All this hassle and it's not even working btw :c
Like I tried it on a Vector3 as per their docs and I could still edit the vector grr
Yeah so there's nothing I can do about it. For future reference: NaughtyAttributes works super well... for MonoBehaviours. It doesn't work on scriptables
I ended up just doing this
it should work on scriptable objects just fine. if you have your own inspector however it wont work (unless you change the base class to theirs)
Is it possible to use an interface as target for a custom editor?
Like I have an editor that wants to do: [CustomEditor(typeof(ISerializedRaise), true)] but it's not showing anything
yeah i think it has to be a concrete type
I need to spawn a mesh that would be present in front of the player all the time ?
Would you do the spawning in Awake() or Start() ?
Like as a general rule, spawning things at the start would be done in Awake() or Start() ? Are there bugs that could happen if it was done in Awake() for instance ?
Awake is called before Start. Start is called on the frame the script is enabled for the first time. Technically you can spawn a prefab with disabled scripts and Start won't run until you enable them. Another difference is that Awake is called as soon the script's instance is created, meaning you can't do much beforehand. Example:
void SpawnPlayer ()
{
var player = GameObject.Instantiate(playerTemplate) as Player; // Awake will be called
// Here you can do something before Start is being called
// Start will be eventually called later
}
as Player huh
But here the object I'm spawning doesn't have any script, it's just a preview mesh that's spawning in front of the player telling him that he's in "placement mode" so he can place toys on shelves.
And the spawning is on a script that's on the player himself
Can be useful if for any reason we're instantiating something with a generic reference. Rather rare occurrence. Most times it's better to use more specific references.
just seems out of place in such an example. Also always prefer (T)v casts over as.
Then if you spawn Player and you spawn mesh in the Start method, the mesh won't be spawned if the player had its mesh-spawning script disabled. It's something rarely will happen, but you wanted a potential issues, so I listed this one. I usually spawn disabled objects when I'm optimizing UI, but it's a more advanced topic.
I'm not spawning "Player", "Player" is already in the scene from the get go. I'm spawning a mesh / prefab in front of the player as a visual indicator
The first one is conversion, the second one is casting. I prefer the second one if I want to be sure that one type derives from another one. The first one is better if you're not using inheritance.
er what
Imagine something like this, here the blue thing is the preview mesh I'm talking about which I need to spawn in front of the player at all time and hide it when he's not in build mode
() and as both are explicit cast expressions, lets not confuse people: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/type-testing-and-cast#the-as-operator
() is prefered when we want the cast to succeed (because we get a nice descriptive exception when it fails!)
Then the Player's object is being spawned during the scene loading and the same rules apply. If the spawning script was never enabled, then Start method in the spawning script will never be invoked.
so where do I put it then ?
For the start vs. awake question, it's usually good to do:
-internal initialization in Awake (not depending on other objects and their initialization)
-other initialization in Start (might depend on other objects)
In this case it probably won't matter much
At some point, the object you want to preview could have more than 1 mesh too
what do you mean ?
So it might make sense to draw the preview object with one of the DrawMesh/Rendermesh methods
Like a child object
So recycling a single meshfilter+meshrenderer for the preview would not be enough
In 99% of cases it doesn't matter. In the other 1% cases you either want to do it in Awake (during the initialization, to make sure it's always spawned at the same time the player is being spawned) or in Start (to delay the object spawning until you actually need it). If you prefer reliability over optimization, pick Awake. If you want to make things more optimized and you know what are you doing, pick Start.
Thanks
hey so I'm making something RTS/tower defency. I want to be able to research techs that boost stats of units, think HP + 10% etc. etc. I want a flexible system to be able to apply these buffs/debuffs to all units in an easy and performant way. Happy to go for an asset that does it for me 😛
It would be nice if the same system could also be used to apply temporary buffs/debuffs during gameplay also.
I was reading something about factory pattern scriptable objects, is that like a universally agreed upon route?
This is what I was talking about:
And is Update() called after Start() ?
Yes. You can test it out by adding Debug.Log (Time.fameCount); to your methods - logs displayed in the console will appear in the same order methods were called, and you will also get information about the current frame number.
well yea that makes sense when we see how as works. If an explicit cast operator was implemented this cast could work with ().
So do you confirm that I don't need to check for "null" for the spawnedMesh in the Update() method knowing that Update() is executed after Start() and the spawning is done in Start() ?
When it comes to removable buffs (including temporary ones), I would recommend always storing them as a list of buffs rather than modifying the actual value. I think ScriptableObjects are great for making up presets, e.g. you could create a preset for different buffs (constant values and percentage values), then store them in a list and use ScriptableObjects method to calculate the new value. It would be very flexible solution, but the downside would be bad optimization if you have dozens of buffs applied at once.
Yes, as long no other script will destroy it.
Thanks. " bad optimization if you have dozens of buffs applied at once." so this is something I'm concerned about. not only is it on android it's mobile VR, with potentially hundreds of units.... So the idea of having load of scripts and objects calculating stuff all the time is a bit scary vs. something ike keeping a database of values or something and just loading them all in on start/spawn (obvs wouldn't work for temporary effects). That said I'm GPU bound vs CPU so... And maybe there'd be eg. 3 techs for ++ health, 3 techs for ++ accuracy etc etc and can imagine them all piling up
An optional solution would be to cache your stats every time a buff is applied/removed from the list. It would work well if you access the processed value often or if your buff doesn't affect many stats at once.
does unity have some build-in methods for sanitizing filenames?
do you think on a per unit level? So... in my game, there would be research that you can unlock outside of the tactical level, which wouldn't be recomputed during the tactical (gameplay) level. I was wondering if calculating the stacks of buffs at the beginning into some kinda manager, and then when units are spawned they query the manager... something like that.... although then I suppose that would lead to there needing ot be a separate system for temprary status effects etc etc etc
If some bonuses are being applied outside of the game, then it would make sense to process them beforehand. But it might not work if your system has to be extremely flexible, for example, if you have +5 attack buff and +100% attack buff, then you can't "merge" these buffs without knowing the base stats of an unit. And even if you knew the base stats, then things could be complicated once a new buff is applied. Imagine that you want % buffs to be applied last, that way cached value would need to be split into constant bonus and % bonus. If you get a buff like "+1 attack per 10% of health lost", then you would need to recalculate this value every time health of your unit is changed. In conclusion, precomputed bonuses will work fine, but only if your stat system is relatively simple.
I don't know what sanitizing filename means, but Unity has a method that changes the asset file path to avoid duplicates:
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/AssetDatabase.GenerateUniqueAssetPath.html
It's only for Editor purpose's though (it won't work in build).
You can perhaps try checking for invalid chars in a path yourself:
https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getinvalidfilenamechars?view=net-9.0#system-io-path-getinvalidfilenamechars
You can also get the full path from a relative or partial one:
https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getfullpath?view=net-9.0#system-io-path-getfullpath(system-string)
and ofc the normal path functions for checking if files exist or folders exist blah blah
yeah I'm doing that at the moment but I was curious if unity had some cleaner method
Not sure if there is but i doubt unity would provide it
thanks for taking the time to give me your thoughts 🙏
I'm actually working on a stat modification system rn. I store the base and when the stat is retrieved i apply all saved modifications (which can add and multiply).
How to swap jumping method in StateModes?
Why does my dummy character doing its like on his own instead of being in front of the player please ? 🤔 Like the prefab should spawn in front of the player camera and always stay in front of the Camera of the player even if he's moving but here it spawns under the map
https://gyazo.com/4c06dbb5fff7483e7970dae123ecaa90
What do you think - (Vector3.up * 50) does? 🤔
This part is also wrong:
Don't read the individual components of a Quaternion. xyz and w are for advanced use cases only.
make the object not appear directly in front of the player but a bit lower to not have the head of the object be outside of the camera
why ?
I'm working on a 2d up view game. There would be a car and several paths going from the start to the destination, and it's random which one the car goes on. How should I plan on implementing this?
Read the link i posted after that
How large are your objects if 50 units is considered "a bit"?
Ideally your units should match meters in real life
So 50 meters downwards is quite a bit
I'm really confused by the unit system in Unity, sometimes it feels like I'm using centimeters and other times it feels like I'm using meters
My objects need to be the size of figurines as it's figurine collecting game
I think your objects are just scaled weirdly
Like some FBX being imported 100x too large or 100x too small
right now there's no scale applied
they're the size of a player
Then moving them 50 meters downwards in world space is definitely not right 😁
You could just make the object a child of the camera
Child will automatically follow the parent's position and rotation
Idk if you want a different rotation though
from the video, looks like the camera isnt following the player so maybe the camera is just far down. Though I dont get how the difference between 50 units would be the difference of their head showing up
yes, the "figurine" must always face the player
The orange character isn't the player as here I'm in First Person View, the orange character is the figurine
Just make it a child of the camera and adjust its localPosition and ``localEulerAngles` if needed
Assuming it doesn't need physics or anything
I think I can't do that because later I will need to snap to positions on shleves
Hey Guys
Out of curiosity, I’d like to know if there’s a way to make the new Cinemachine Input Axis Provider to read input even when a player is performing another action cause I noticed while I’m moving or attempting to shoot I’m unable to move and rotate my camera until I stop pressing any of the other buttons
It works, thanks, so yeah the issue is the distance from the camera, the scale of the figurine and me not knowing how to handle quaternions 😄 Now I need to lower it down as I said as here the head is outside of the camera and also make the figurine face the camera.
Is there a built in method to "LookAt" and object ? Or do I have to write it down myself ?
There is a lookat method yes (literally transform.LookAt) but I don't think you want exactly that
You can add a rotated offset to its position
why wouldn't I want that ? 🤔
Oh oops i assumed you want to rotate the camera towards the figurine
Okay so other way around
transform.LookAt might be enough
@fiery steeple You probably still want this though^
Move it down a bit?
You can do something like previewMesh.transform.position += cameraTransform.up * -1.23f to move it down relative to camera
Got that already working 👍
why ? 🤔
You said the head going outside of the camera was an issue 🤷♂️
Oh yeah that part I solved it with an offset, thanks 😄
I used this
so I can have a vertical and horizontal offset
Those aren't relative to the camera but if that's fine then sure
Try looking around a bit and straight up/down
how isn't that relative to the camera ? 🤔
ok let me do that
You are just adding Vector3.down/left to the world position
So I should do it relative to the camera ?
Pretty much replace those Vector3.down/left with -camera.transform.up and -camera.transform.right
transform.up/right/forward are in world space, but relative to the transform
still same issue with this
fixed 😄
For some reason the raycast doesn't detect my shelf
First take out the layer restriction, if it works after that the layers are wrong. If it still doesn't work, take out the distance restriction and if it works after that, the distance is too short. If it still doesn't work the object doesn't have a collider
without the layer it works
Note that layer and layermask are different things
The distance I set it to 10 so I'm kinda confused on why it doesn't work knowing that 10 = 10 meters and the ray in the Scene Preview the ray looks long enough to intersect with the shelf
ah, what's the difference ? 🤔
If it works without the layer restriction then obviously there's nothing wrong with the distance
LayerMask is a bit mask that basically stores one flag per each layer within its 32 bits
You can just declare a LayerMask instead of an int layer and use that
That's what I declared at the top
that NameToLayer call is wrong, it should be GetMask instead but you should just get rid of that line and assign the mask in the inspector
It works, thank you so much 🙂 👍
how do i make a* know the agents size like navmesh got the radius
is this your own implementation of the algorithm or are you referring to a specific asset?
look at the inspector for the AIPath component
bruh how can i miss this 😭 thanks
Save data should be handled with DTO object. With some JSON library, you can embeded the type of the given object in the save if you need.
Alternatively, you can serialized in two step.
{
"WorldState": [
"id": "..."
"data": "Other Json"
]
}
You can create automated class serialization with JsonUtility:
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/JsonUtility.html
Keep in mind that automated serialization might try to serialize things you don't want to serialize. In the end, it's better to do things manually
Here is a Unity package that adds some JsonConverters that improves serialization for Unity classes:
https://github.com/applejag/Newtonsoft.Json-for-Unity.Converters
And here is an example of Vector3 converter:
https://github.com/applejag/Newtonsoft.Json-for-Unity.Converters/blob/master/Packages/Newtonsoft.Json-for-Unity.Converters/UnityConverters/Math/Vector3Converter.cs
The idea behind using a DTO is to separate data that are not serializable from data that are.
can someone help me? when i double click on a script in my game and im wanting to edit it why does it ask media player or notepad
You could have the following.
[System.Serializable]
class EnemySave
{
public string ID;
public string Data;
}
Obviously, it would assume that each enemies are already known in advance.
Do you have an !IDE?
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
One of those ^
ide? if you mean id yes i do
IDE is your code editor
Integrated development environment. In other words, a code editor.
idk im new to unity
You can delay the deserialization to whenever you know the type. By example, in case of a door, the door could look to see if there is a save with the given ID. From there, you know what the serialization type is.
IDE is a separate program of your choice. During Unity installation you had an option to also install Visual Studio. Alternatively, you can install it (or another IDE) manually.
i never got that option
It looked like this:
i think a few months ago when i first downloaded unity i tried making a vr game so i downloaded stuff but i forgot where to get that stuff
Also, you might want to use polymorphism with your class, you can with Json. Alternatively, you save multiple object, one per class parent.
DoorSave
SpecialDoorSave
SpecialDoor : Door
or
SpecialDoorSave : DoorSave
SpecialDoor : Door
It probably is here:
C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE
The version number can vary though.
Yes, it's not the same.
Hey is there a way to use a blit with a custom shader such that it doesnt take 3 drawcalls?
I am confused where a lot of the cost is comming from here(the only thing the blit does is to merge two textures together using alpha blending)
hi there, i'm encountering an issue when loading a scene a second time during the execution of my game.
game objects are keeping old references to their children gameobject in serialize fields which result in a MissingReferenceException.
do you have a any idea how to deal with this behavior? i was expecting that my object will instiante his children and refresh his serialize fields
thanks!
sounds like you may have a DDOL object that either shouldn't be DDOL, is doing too much and wouldn't need those references, or you need to update the references to those objects when the scene is loaded again so you are referring to the new, existing ones
Hello. I am having some trouble getting foot IK right. I can't find a way to set the target for the IK right after the animation frame. I don't think I have a full grasp on what happends when. I found a post theorizing that the animation update happends before the component lateupdate, but then I would think that this would work. Anybody that sees my mistake? (don't mind the foot normals)
public Transform left_ray_from;
public Transform left_ray_to;
public Transform right_ray_from;
public Transform right_ray_to;
public Transform left_target;
public Transform right_target;
public float raycastDistance = 3f;
public LayerMask cameraWallLayer;
void LateUpdate()
{
AdjustFootTarget(left_ray_from, (left_ray_to.position - left_ray_from.position).normalized, left_target);
AdjustFootTarget(right_ray_from, (right_ray_to.position - right_ray_from.position).normalized, right_target);
// AdjustFootTargetVertical(left_ray_from, left_target);
// AdjustFootTargetVertical(right_ray_from, right_target);
}
void AdjustFootTarget(Transform rayOrigin, Vector3 direction, Transform footTarget)
{
if (Physics.Raycast(rayOrigin.position, direction, out RaycastHit hit, raycastDistance, cameraWallLayer))
{
footTarget.GetComponent<TwoBoneIKConstraint>().weight = 1;
footTarget.position = hit.point;
footTarget.up = hit.normal;
}
else
{
footTarget.GetComponent<TwoBoneIKConstraint>().weight = 0;
}
}
im manipulating 0 ddol object in the scope of this issue, and when i'm looking at the hierarchy tab during runtime, the object is indeed disappearing.
but on the scene reload, wrong references
show the object(s) inspector and the relevant code
It's not possible for them to keep the old references unless they are being persisted somewhere - most likely in DDOL
If they are truly being recreated along with their scene there are no "old" references to hold on to, because they'd be completely different objects
In an open world 3d game, i have multiple biomes and i want to play different music depending on the biome in which the player is located. How do i get to know in which biome i am right now?
here is the structure, LobbyUI has a PauseMenu script which enable the gameobject on an event
public class PauseMenu : MonoBehaviour
{
[SerializeField]
private GameObject pauseMenu;
[SerializeField]
private Button exitMenuButton;
private bool _enable = true;
private void Start()
{
PlayerLogic.OnGamePauseToggle += OnGamePauseToggle;
pauseMenu.SetActive(false);
exitMenuButton.onClick.AddListener(() =>
{
NetworkManager.Singleton.Shutdown();
CustomSceneManager.LoadScene(SceneName.MainMenu);
});
NetworkManager.Singleton.SceneManager.OnSceneEvent += OnSceneEvent;
}
private void OnGamePauseToggle(object sender, PlayerLogic.OnGamePauseToggleArgs e)
{
if (e.Show && _enable)
{
CameraManager.Singleton.EnablePopupMode();
pauseMenu.SetActive(true);
}
else
{
CameraManager.Singleton.DisablePopupMode();
pauseMenu.SetActive(false);
}
}
do you procedurally generate the world or is it hand crafted?
hand crafted
so it is the pauseMenu and exitMenuButton fields that are being reset to old references?
yes the error is happening on the pauseMenu.SetActive(true); line
if it is hand crafted you will probably have to create triggers which trigger a music change
right and that is because you are not unsubscribing your method from the OnSceneEvent
hooo, subscribing an event makes the object not being deleted 😮
no
A quick tip on making simple triggers with unity events
Follow me on twitter: https://twitter.com/passivestar_
Join our Discord: https://discord.gg/pPHQ5HQ
what's actually happening is that the method is still being executed when that event is invoked but since the objects being used have been destroyed it throws an exception when it tries to use them
that works, you really rock. thanks a lot, i've been stuck on this for way too long
it makes so much sense now, i now understand why people are unsubscribing event in tutorials :p
thank you, i will try that i guess, doesnt feel completely satisfactory because i see already there will be some issues that will have to be covered with unknown amount of codechecks but who knows, maybe it will do good
hmm, maybe you could set up a proximity system, let's say you put down some gameobjects and maybe every x seconds you can check to which gameobjects you are closest too. On that game-object you can define a track that plays? Maybe you can blend between tracks?
i was kinda thinking about it before i asked my question but it also has its own issues but it is much more reliable because if players will get throught the triggers wall in an unexpected way then... i need to monitor those triggers all the time if anything changes in the world
and with distance checks its more flexible to changes in the world, so yeah, both methods sound good but also unfinished
i was expecting to hear something like terrain checks of the layer and also maybe some color maps
what version should i get? unity 6 or?
well, you can make is as complex or simple as you want. If you need finegrained control and you are using some kind of terrain tool then you could use a texture with different colors for different tracks?
and what if i'd answer that i use procedurat terrain, is there some good solution to this?
i never used any
then you would probably need to also generate that track texture along side your biomes
thank you for the help 🙂
no worries
Unity version is irrelevant. You only need any program made for coding. You can install Visual Studio by adding modules to your Unity's installation (as in screenshot). Alternatively, you can download it from here:
https://visualstudio.microsoft.com/free-developer-offers/
Here is some video tutorial:
https://www.youtube.com/watch?v=unTVDwHxq8Y
Hi everyone, I'm playing around with loading and unloading scenes asynchronously using the SceneManager.LoadSceneAsync, and come across a bit of a problem.
I have a manager scene that controls which scenes to load additively and then which to remove. Ideally I would like the behaviour of seemlessly switching between the two scenes. This could be fine, however their is a chance that the scene can swap into instelf.
Since the Loading of scenes taxes either their path or the build index, this means their is no way to destinguish which scene I want to load and unload from the copies? How would I do this?
(Specifically, I have 2 versions of the same scene loaded, I want to unload 1 which is the older version, how would I go about removing specifically this one).
I have found that UnloaScenedAsync can take a scene itself as an arguement this solves half the issue, now the problem would be to get the loaded scene from the LoadSceneAsync function
whats wrong with the other functions
to get the scenes
These will return the same name would they not? If I have two scenes with the same name I cannot differentiate between them
The project is an example project for a class where they are making a WarioWare like game, once the "microgame" is completed it then calls another from the collection. This means their is a chance that it can call the same game again to play.
Meaning that I am then unloading scene "mini-game A" and loading "mini-game A" again, which causes a problem as then Unity gets confused between which scene I mean to be loading and which I mean to be unloading.
So I would need to use a way of differentiating scenes in runtime, without using the scene build index or its name
I do recognise that this "can be solved" by just not allowing the same mini-game to be played twice, however that isn't the purpose of this excercise and I would rather have the functionality to reload the same scene then locking myself out of it.
Is their a way to find the most recent scene, and then rename it?
why not load into a load scene, unload the old scene, then load the new one? that way you can never end up with collisions like that
The scenes are meant to be very quick, so mini-games in around 5 - 10 seconds, so having loading scenes would be a bit much. Ideally I would load the "next" minigame while the current one is being played.
Then activate it once the current minigame is complete
This is the kind of thing I am trying to accomplish
The students would each work on their own scene, and then at the end given they add a call for Success or Failure, the minigame manager should automatically transition between the minigames.
But to do so, they need to be ready and waiting to be swapped in.
this hurts my adhd
xD
isnt there a scene inbetween those
Some of them, but others no
Some just trainsition imidiatly into the next mini-game
Though that said, the minigames dont repeat, so they arn't facing the same issue (not that I know if WarioWare was made in Unity or not or some bespoke engine)
But does what I need it for make sense now?
I still assume SceneManager.GetSceneAt could get you the latest scene and pass that Scene object to the Unload
Is it always garanteed that the most recently loaded scene would be the final scene?
tbh I havent messed with this too much though so take it with a grain of sault
If so then that would work perfectly
Ah okay, well Ill give that a shot for now, and see how it works. It may work wonders!
Yeah
goodluck 
So far so good!
I have tried multiple scripts for parallaxing in Unity 6 2D URP but can't get any to work properly. Is anyone able to help me?
show what you tried and explain what isn't working with that attempt
If I have a cylinder, how could I find the point that has the lowest Y axis and is positioned on the top edge of said cylinder?
I may have worked it out but if not I'll let you know
yo can somebody help me make my car controller not feel like ice?
Not sure what you mean with the top edge, but I have an idea how you could solve it, it's probably not the best. So your cylinder is defined by certain rotation, which is a certain direction. This direction is the normal of the top circle. That normal and the middle point of the top circle define a plane. Also the y-axis and that normal define a plane. The intersection of those 2 planes forms a line, the intersection of that line and the circle gives you 2 points. The highest and the lowest, take the lowest
There is probably a simpler way, also depening on how your cylinders are defined.
@granite frigate Please don't crosspost. #💻┃code-beginner
ok,but if youd help me that would be great
I don't think ArrayList<T> exists
Just use a List<T>
it does, it's just a non-generic type
Or T[]
How does it know what it contains ?
it doesn't, that's why it's bad and you shouldn't use it
So.. not ArrayList<T>
But ArrayList instead
I think it's because of Java that it confused me because in Java they call it ArrayList<T>
You can do a foreach loop on a transform to get its children btw
That's what I'm gonna do in that method
guys is it a good way to code a ability system for a roguelike where alle the skills are 0 at the start and if he like choses a specific skill in the popup the skill index is 1 so the program knows that this skill is active since its not 0 or is there a better way to handle skills for a roguelike. Like how should i do a skill system ? thts the only plan i had
If you're just using 0/1 for active or not, you may as well use a bool.
If the value can increase higher than 1 with levelling up, then sure, use 0 as inactive state.
sometimes, it makes sense representing 0 - 1 as false/true state
mainly for branchless stuff
yeah it can increase so is it a good way you would say?
yes i know but the main thing in a rogue like is to increase/level up yk
so i thought it might be a good way to make the number increasable
yeah, nothing wrong if that's reasonable enough
nobody really uses ArrayList nowadays, all ArrayList can do, List<T> can do much better
Tho what's the difference between ArrayList and List ?
well, if it's value types you're bound to boxing (due to object to T casting)
even if they're ref types, you must cast them whenever you want to get something from it
that said, no reason to use ArrayList at all unless for legacy reasons (supporting old apps)
also you can do this with arraylist
arrayList[0] = "something";
arrayList[1] = 1;
arrayList[2] = `c`;
that's just super bad
You get better type safety with list<T> if im not mistaken 🙂
i didnt read the above
much better answer than mine lmao
the type safety is just the nature of generics, but yeah, that's true as well
i need help debugging this
plss
when i crouch or sprint the character starts bugging out and the humanoid render splits apart from its parent obj
I did omg ty
hey i need help with this code, i was trying to encapsulate the exact size of the model (and the rearmost point) but the problem is if i rotate the object the frame changes, so the code only works with a rotation of 0,0,0 , maybe i am just being dumb rn
using UnityEngine;
public class DrawFrame : MonoBehaviour
{
private MeshRenderer[] objectRenderers;
private Vector3 boxCenter;
private Vector3 boxSize;
private float rearOffset;
private void CalculateBoundingBox(GameObject ship)
{
if (ship == null) return;
objectRenderers = ship.GetComponentsInChildren<MeshRenderer>();
Bounds bounds = objectRenderers[0].bounds;
foreach (MeshRenderer col in objectRenderers)
{
bounds.Encapsulate(col.bounds);
}
boxCenter = bounds.center - ship.transform.position;
boxSize = bounds.size;
rearOffset = FindRearMostPoint(ship);
}
private float FindRearMostPoint(GameObject ship)
{
float minZ = float.MaxValue;
foreach (MeshRenderer col in objectRenderers)
{
Vector3 localMin = ship.transform.InverseTransformPoint(col.bounds.min);
if (localMin.z < minZ)
{
minZ = localMin.z;
}
}
return minZ;
}
private void OnDrawGizmosSelected()
{
CalculateBoundingBox(gameObject);
if (objectRenderers == null || objectRenderers.Length == 0) return;
Gizmos.color = Color.green;
Gizmos.DrawWireCube(transform.position + boxCenter, boxSize);
Gizmos.color = Color.red;
Vector3 rearMostPoint = transform.position + boxCenter + new Vector3(0, 0, rearOffset);
Gizmos.DrawSphere(rearMostPoint, 0.1f);
}
}
the animation I'm using from mixamo for crouch is aimed slighted towards the left which looks pretty bad, what's the most efficient way to fix this?
get a different animation?
this is a code channel
Hello there, I am using awaitables right now and wondering, how to prevent it to be in a detached state. Simple example calling this from a delegate in another script will fire, that joiningTask is in a detached state. I am sure, its a simple fix but I was expecting the completed check to be enough to avoid it.
private async void JoinVivoxChannel(string userId, string channelName = "DefaultChannel")
{
if (joiningTask != null && !joiningTask.IsCompleted)
joiningTask.Cancel();
joiningTask = JoinVivoxChannelAsync(userId, channelName);
await joiningTask;
}
Or do I also have to work around the cancellation with a token?
There is also some example code in the docs to wrap it in a task, which would lead to token usage. But maybe there is some way for awaitables to do on their own?
not sure without being able to debug it but this might have something to do with Awaitables being pooled objects, i'm not sure it's safe to keep a reference to one after it's been completed because it could be reused for something unrelated
a cancellation token should solve it in that case yeah
thanks for the help.
Will try it 👍
Unitask pools tasks and they cannot be awaited more than once, i think unity does the same
also change the return type to awaitable! otherwise it will be a .net Task.
how can i use animation curves to increase my brake power the longer i hold the button? (new input system in unity 2021.3)
👀
curve.Evaluate ?
pass time.delta * amount while holding btn
use the higher value at end of curve for braking power
ye i tried
whats the issue then ? show what you tried and what is your current result
called every FixedUpdate
void ApplyBrakeForce()
{
if (moveDirection.y < 0)
{
BrakeTime += 0.2f;
Debug.Log(BrakeTime);
}else
{
BrakeTime = 0;
}
rb.velocity /= (1 + BrakeCurve.Evaluate(BrakeTime));
}```
but doesnt do anyhting
this doesn't look right..
have you tried also debugging the return value instead of just "eyeballing it"
at minimum even in FixedUpdate I would add Time.deltaTime in the horizontal eval
or breakTime
yes im new
i'd probably use Evaluate inside of update anyway, then use a Brakepower var or something in FixedUpdate
it worked before without animation curve
we print / debug the value that you are getting and see what its actually doing
you cannot go with blind assumptions right away
i think i have a problemo, it doesnt work at all now
idk what "it doesn't work" mean nor what you did and didn't do lol
the entire car controller
idk what you expect anyone todo with this information only and nothing else
when rapidly decreasing size, how can i prevent the object from being 'mid air' before it falls back down, as in how can i keep it on the ground as it is decreasing? i feel like just adding a negative y velocity will lead to some issues in the long run
pivot point to bottom left/right corner, or scale and adjust position as you scale
let me try the pivot point, out of curosity, what would that math look like for adjusting position?
Yeah I’d think ray cast down as you change size to check where the ground is so you can correct the position.
But also just making the pivot at the bottom might make that unnecessary
ya like everything in any solution there are pros and cons of each
the latter (position adjust) requires a bit of math
account for the bottom half from the center point and use something like ray to find the ground etc
Yeah if just making the pivot at the bottom does it then I’d just stick with that
for changing the pivot, i have to make it a child of a 'pivot' object right?
in 2D you can just use the sprite editor
but ideally you always want your grafix separate from your parent
Only thing is that might mess with other code that’s checking position
yeah just be aware your pos will now be at "the feet"
transform.position
im having problems with this
rb.velocity = new Vector2(0,0);
its not slowing the Player down
Need more context
show entire !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
and how did you verify that line is running
i fixed it
does the URP support caching shadows for baked objects?
you should probably ask that in the #archived-urp channel
Is there a built-in method to calculate distance between 2 positions or should I create that method myself and the math in it (the math is easy but just wanted to be sure) please ? 🙂
if you google "distance between 2 positions unity" you'll see the built in methods, there is Vector3.distance
Thanks 👍
Other question : Do you recommand using Transform or GameObject when dealing with objects in the world through C# script ?
Those are different things. It's recommended to use the one you need
you rarely need to directly access something by the game object. if you want to move something then its going to be by the transform
I heard that they're almost similar
It's like comparing a wheel and a car
Transform is part of the gameobject
It's just another component, but it's special in the way that a gameobject always has a transform
Yeah I know that but here I'm more talking in terms of recommendation of which one to use because alot of the times I do this :
- When I use a Transform, sometimes I have to do this
transform.gameObject - When I use a GameObject, sometimes I have to do this
gameObject.transform
if it doesn't have any other components i generally use a [SerializeField] Transform
https://youtu.be/B-dVf9wUEbg
Like what do you think about the statements in this video
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
🎮 Get the Polygon Heist pack https://cmonkey.co/synty_heist_gameobjectvstransform
👍 Learn to make awesome games step-by-step from start to finish.
👇 Click on Show More
🎮 Get my Steam Games https://unitycodemonkey.com/gamebundle
🔴 RELATED VIDEOS 🔴
Why you should NOT make everything...
its more likely you're gonna use transform than gameObject
Thanks 👍
And what do you think about the video above ? 🙂
there is very rarely ever a need to refer to an object by its GameObject, use the component you actually care about instead
haven't watched it, I generally don't agree with what this man says
Please watch it (it's only 7 min) and would like your opinion on it 🙂
he said in 7 minutes what i basically already said lol
Bruh, how did you watch 7 min when I started the video before you and didn't finish it yet 🤣
I skimmed through it with 1.5x speed
I skim through things and I understand their context
Damn I wish I have a brain wired for 1x5 like you guys 🤣
so usually I stick to transform when there is no components, and if you have a component use that eg [SerializeField] MyFancyScript
since all components can access both gameobject they're on and their transform
Oh because if there are other components you will have to do something like this : transform.gameObject.GetComponent<T>().blabla instead of just gameObject.GetComponent<T>().blabla?
You can get component from ANY component
that includes Transform
transform.GetComponent<T>().blabla
oh 🤔 Then I'm not sure to understand what's the reason of your choice 🤔
choice of what?
To usually go for Transform but if there are other components go for GameObject
no if you have other components you typically interacting with a main one , eg MyComponent from there you can access transform too so you don't need a serializefield transform
I don't understand 🤔
[SerializeField] MyComponent myComp
myComp.transform.SetParent(whatever)
myComp.CoolFunction()
myComp.GetComponent<MaybeAnother>().Something = 3223
etc
Ok but I don't see how does that answer my question 🤔
which question ?
To usually go for Transform but if there are other components go for GameObject
I never said if there are other components use GameObject
This one yeah ☝️
If there are other components, reference the main one you will be interacting with
Oh, then I misunderstood 🥲
I’m guessing that transform.GetComponent calls transform.gameObject.GetComponent under the hood anyway
So it doesn’t really matter
Just use the type that has properties and functions you’ll be using
get component comes from Component not GameObject
Sure but gameobject also has a GetComponent so likely the components just call that
Ah okay didn’t know that. But can’t you do gameObject.GetComponent?
ofc
But gameObject doesn’t derive from Component does it? I actually don’t know
GameObject is also a component
oh right its the root , brain aint brain today 🚶♂️
Which is also the root class for scriptableobjects, components etc
Someone made this statement, what do you think :
*The two types have two jobs. They have direct links to each other, but use the type that makes sense for what you're doing. If your primary need is about position or parent/child relationships, Transform makes sense. If your primary need is instantiation or activation or dealing with the object as a whole, GameObject makes sense.
And if your script really is only interested in a particular component like a CharacterController or something, use that type reference instead of either of the others.*
That I think sums it up well
reasonable
That's again pretty much what we been saying
I don’t think this is true though. But I don’t have a project at the moment to confirm. I’m pretty sure GetComponent belongs to GameObject and Transform is just a special case
its here
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Component.html
Transform inherits Component like other MBs
AddComponent is for gameObject only. Maybe you are thinking of that
Ah yes you’re right
In any case this is also probably correct
seems reasonable yeah since thats the "container" of all components
I love how they say
ScriptableObject as a way to create scripts that do not attach to any GameObject.
poor Poco
But yeah if you just keep “Don’t repeat yourself” in mind then reading your code will tell you whether you’re using the optimal type reference
Do we agree that declared variables inside methods (here Update), the next time that method is called it doesn't save the previous values in those variables anymore ?
well yeah thats a good thing lol
Its just a normal privative cylinder mesh. All I want to do is get all the vertices along the edge of the top face, and find the lowest.
what are you trying to accomplish? Maybe that will give us some insight for a solution?
Well, that. Finding the lowest point on the top face edge of a cylinder
what is the further purpose of it?
if it's a cilindrical mesh and you need a vertex, I might suggest looping through the vertices and finding the one that you need
The point where a liquid would pour out of from a cylindrical container (ie. a cup)
Yes, but how can I find only the ones on the top face edge
that's a bit tricky depending on the cilinder, but you could probably set a condition to find all top ones: vertices who are in the radius of the top circle. then you take the lowest one
or maybe you could define some points yourself? add them to the mesh, then take the lowest one
Yeah but then you cant get a exact point unless I made a lot of points
well, your vertices are also limited
@turbid pagoda if you want an arbitrary point I would suggest doing something like this:
calc the blue point
you can do it with the normal, and it has to be in the same plane as the y axis
and perpendicular to the normal of the cilinder
or actually, you just mirror the normal around the xz plane, then you scale it by the radius of your top circle and you should have it
my game currently involves lil robot guys that travel through space towards scrap which it then brings back to a storage object. Ive currently been doing this using just the lookAt feature then basically ramming the object forwards in the hopes it hits it, which worked well enough, but i kinda need it to not hit things on the way, which means i need pathfinding, which means nav mesh, but i dont have any clue how to get it to work on open space, or if it even does work
as you can see my lil green guys arent very good at reaching what theyre meant to due to terrible overshooting and lack of pathfinding from my current method
3d
ye
👍
very poor so will look online for a solution first then maybe try my own method
Hey, I don't understand why when my raycast detects an object that has the interactable layer mask it sets the position of the figurine preview in front of me to a position inside me (the player) instead of snapping to a placement spot inside that object with interatable layer (in this case it's a shelf that has empty objects children as placement spots.
sorry what are you expecting to happen here and what's going wrong instead? The video is a bit confusing
What is supposed to happen is that when I hover over that shelf (so when the raycast hits that shelf), the little orange guy is supposed to snap to the closest placement position in that shelf relative to the point of impact of the raycast.
In a summary I'm trying to create the placement of objects on shelves mechanic.
https://gyazo.com/4bb5c04635464cb99ccc9bb6318d1727.mp4
This is the mechanic I'm trying to achieve
Need some help with a package I’ve made: It contains both runtime and editor components, AND uses OTHER packages I’ve made, so I created two assembly definition files, one for editor, and one for runtime. The editor asmdef is shown in the image below. In the unity project where I have this package defined, everything compiles without problem.
Problem: When I import the package into another project, I get the following compiler error:
Library\PackageCache\com.glurth.memberexposer@d01f2037f9\Editor\DataTypeToDisplayPrefabMappingEditor.cs(133,30): error CS0115: 'DataTypeToDisplayPrefabMappingEditor.SaveChanges()': no suitable method found to override
Which makes no sense because this class derives from the UnityEditor.Editor class,which DOES indeed have this override-able function:
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Editor.SaveChanges.html
Here is the class declaration.
public class DataTypeToDisplayPrefabMappingEditor : UnityEditor.Editor```.
I SUSPECT it has to do with the asmdef, and resolving UnityEditor
Yooo, I got a problem with rigidbody2D which it doesn't detect collisions.
This is in Unity 2D and I have my character that jumps and I want to make him fly if I press "p" , making him "kinematic".
and to make him not fly I want to press "p" again while flying to cancel it but when I do that the collision doesn't work
I belive rigidbodies have an option for if they use gravity or not. suspectTHATis what you want to set instead. @night nebula lemme see ifI can find it.
okok
really apreciate ur help
kinematic ignores collisions when you move it
(others dynamic rb can collide to it, but itself doesn't get stopped by colliders)
it didn't work
I use unity2D
I did this tho
you should configure your IDE.
Rigidbody2D doesnt have a useGravity bool
OnCollisionEnter is not for 2D
the signature is wrong for that 3D one and it should say so in IDE
whoops! Rigidbody2d.. perhaps this one? https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Rigidbody2D-gravityScale.html (never used it myself, but looks promising)
they should configure their IDE first
also rigidbody does not contain "useGravity"
😭
because they told you need gravityScale
also configure your IDE its part of the requirement here
there are TWO classes in Unity, Rigidbody, and Rigibody2D. Rigidbody has the useGravity member, but rigidbody2D has that "gravityScale" member.
this really belongs in#💻┃code-beginner
btw
it would be easier for them if they can actually see all the members when they use . operator
I have configured IDE can I have answers now 😇 
sorry!! whats an IDE?? 😭 😭
the Code Editor
now that definitely belongs in #💻┃code-beginner
your question belongs here actually #↕️┃editor-extensions
totally missed that channel
will move over :3
same thing #↕️┃editor-extensions would probably be more appropriate
figured my editor extension works, just not as a package. is that a better sub for package help?
oh you're making custom package not editor stuff ? I suppose here is fine
Anyone please ? 🙂 ☝️
I'm not sure, looking at the code I dont see anything obvious, but I could just be missing it. Suggest adding lots of Debug.Log stuff. log the NAME of the raycast hit object, log the name of the objects in the placement list, log the layers of each' etc... This will help narrow down the issue- you'll be able to see at a glance it the raycast check is passing somthing unexpected.
I don't know if this is for sure the issue, but if you GetComponentsInChildren<Transform> I found out that the transform is technically a child of itself, so this may be that issue in another form
so when you add the transforms to the list, try checking if the transform it's looped on is itself and if so continue
and instead of making it nullable personally I'd allow it to return an empty list and just see if it's empty instead of null, might just be preference though
no, that method is poorly named because it gets components on self and all children instead of just children like the name seems to imply

although I am now looking at that function and seeing another error
you check obj.transform.childcount but when you loop you loop on transform, should that instead be looping on obj.transform?
Wait what ? I'm not using GetComponentsInChildren<Transform> in my code 🤔 I'm not sure to understand
no I wasn't sure if it would be the same issue in your getchildren function though, but I've been corrected that my reasoning for thinking that is an issue with the unity function not the way they handle children
you're the boss https://gyazo.com/dc77ae881e42cd2bd81b02ccb4193499.mp4 , Thanks 🙂
Could you explain a bit more what was my mistake / why is it a mistake what I wrote please ? 🙂
you're trying to loop over the children of a transform of a specific object, so you've done the right thing in specifying obj as a parameter. A couple lines later you then accurately check the child count of that object using obj.transform, which is the transform for that specific object. However, a few lines later you iterate over transform. transform is a transform so it's not going to cause an error, but it will be the transform of the object that monobehaviour is attached to, which is likely the player. By specifying obj.transform you change it to specifying the transform of that other object 🙂
Thanks 🙂 👍 Now I need to fix the rotation of the figurine preview when it's in the shelf, where should i do that ?
I guess here ?
Thanks 🙂
This is for a FPS platforming controller. I want to add external forces like Rocket Jumping into the game. However, my Speed Difference system cancels out all external forces. Are there any other ways I can maintain tight turning speeds without compromising external forces?
https://scriptbin.xyz/jesikemime.cs (Only the Run and Apply Friction are really relevant for this question)
Use Scriptbin to share your code with others quickly and easily.
You can add a cooldown or a sort of fadeout so it uses the rocket jump movement for a moment and then blends back into normal movement
I didnt really read your code, just an idea.
I understand what you mean. I think it's a solid idea. I'll try it out and let you know the results
Do you have any idea how I would add a system like momentum conservation?
What exactly do you mean with that, gameplay wise?
There is a #⚛️┃physics channel btw. Its a bit less active but perfect for these questions
Oh yeah good point. Didn't even consider it to be a physics question
Hi there, I'm making a button remapping system for my uni project. I just want someone to tell me if my way of doing this is stupid and that there is a better way or that my way is okay. I don't trust my team to not randomly add new buttons so I'm making the buttons on the fly from the input actions script.
I'm making a button that gets added to a list for every item in the input actions asset that meets certain criteria to show up. And each button has a class on it that stores the button object itself, the InputActionReference and a sub reference for things such as WASD to make multiple buttons from the same action reference or if there are multiple buttons for the same thing.
Haven't done much else yet like actually changing the key binds but I want a sanity check as I've been doing ui stuff seemingly non stop for the past few days minus a 4 hour drive and sleep and what not. I'm just slow at getting work done
Games often have some restrictions regarding to the controls menu, such as removing the "change binding" input from the list or locking inputs related to UI navigation. It might be wise for some games to create each option manually. In the end you'll probably want to localize these inputs anyway. Automating the process can be helpful, but it's worth remembering that you may encounter cases where you would want to modify some entries yourself.
hmm, makes sense. I can't lie I'm just struggling to get my head around the button rebinding stuff for some reason. I feel like I'm throwing stuff at the wall with little to no feedback on if what I'm doing is right or not because I wont be able to see if it works until its done
everything else I've done on this project I've had some small little progress bits here and there which makes me feel like I'm actually doing something. But this just isn't
its annoying
so right now I have to ensure only one of these components exists at a time in any given scene, and the way I'm thinking of doing that is giving the class a static 'instance' variable that's set in the Awake() method and will never set it if it's already been set. This exists so other scripts can get the instance of the script without having to do GetComponent<>(). My main worry is if this causes a circular dependency or not, to my knowledge it shouldn't be since the field is marked as static so it exists globally and not per-instance (which is what i want anyway) but I just wanted to check in case im being paranoid or if there's a better way to go about this
what you've described is the typical way to implement the Singleton pattern in unity so it is perfectly fine. Just make sure to set the instance in Awake (and do your destruction of extras there too) and never access it before Start. i'd also recommend making that a property rather than a field just so you can make the setter private
also there is nothing wrong with a "circular dependency" in this context or most contexts since nothing bad will happen if an object references itself. usually the only issue with something like that would be with serialization but that's not going to be relevant here anyway
ah thats good, just wasn't sure if it would cause any massive issues since I saw a similar type of thing in a different script I use for a different project and tried to replicate it here so I'm glad that I managed to get it right, thanks 👍
Not correcting just asking, Is it not safer order of execution wise to grab it in the getter rather than awake?
what do you mean by "grab it in the getter"? as in assign to instance in the property's getter? because if so, that would require it to instantiate a copy manually in that code or use a terrible Find method, the first may not be ideal if they want to do any inspector setup, and the second is just unnecessarily slow.
So while yes, that would solve execution order issues it may not be ideal depending on their needs
Fair. i figured FindFirstObjectOfType<> was not too bad of a sin in the context of when singletons are first accessed but i hear you. ty
just curious, does "fp" stand for fragment passes?
My guess is files processed.
It depends a lot on what you need for the singleton. Should it be accessed outside of playmode? Do you need to access it on Awake of an object for some particular reason? Is the lifetime of this singleton supposed to be bound to the application or to a specific scene? Are you supposed to be able to check for null or should it never be null? Etc.
good try... but it means fragment program/portion or sometthing like that .. so far i know...
uhhh, sup everyone, i am not really sure this should go here, but i have a somewhat design / math question?
Basically i have a list of rarities with 100% total, each rarity having their own percentage.
Inside those rarities there are objects with "weights" which are not %. When i pick an object i sum all the weights, do random and flip through the list to find the needed object.
Basically, i was wondering if it would work the same in terms of chance if i made a single list of objects and just made the weight like
int weight = Mathf.RoundToInt(rarityPercent * itemWeight / 100);
This formula seems weird to me, not really sure what the goal of it would be. What you're currently doing with the objects seems fine and is pretty standard for a weighted randomness
yeah, i can't shake the same feeling.
Basically i have a big library of mobs, they have rarity and weight in that library, so that some mobs are more common than others even though all of them are Rare for example
and i have a spawner object, which is a pain to operate with a bajillion different lists, tons of foreach loops and stuff like that, that in the inspector sets itself the correct mobs he can spawn through flag correlation.
and so i'm trying to optimize all this
Oh wait, are you doing 2 selections here. Like selecting a rarity, and then summing up the weights of that list only?
I think I can see what you were trying with that formula if you're summing up every single rarity in one list
yeah, since its like rairty is a percent from 1 to 100
its just weighing percents
for each item
no?
I'm not sure if you know what I'm asking you
i am honestly confused by now
i'm trying to access a self made script from a script which was included in a package in which i'm editing a method to change a bool in my own script. however for some reason i can't access my own script except from my own other scripts. I can access the scripts form the package through my own scripts, usually when using namespaces.
the package is 'code monkey toolkit' None of the scripts are accessible through newly created scripts. other way around works normally.
oh, yes.
The process right now is having separate lists corresponding to a rarity, a random method to pick a rarity with %, and summing weights in that single rarity
but since its a spawner and it has 5 different lists, it feels very unnatural, clunky and very uneasy to use, so i'm trying to see if modifying the weight of the item with the rarity percent will produce the same random chance result
Ok yea that's better than what your initial formula was suggesting then.
is it possible to achieve a single list of items with the same chance results if i just do itemWeight = Rarity * weight
cause it feels right and wrong at the same time?
A #if UNITY_EDITOR method i devised:
0) Create a single availableItems list
- For each rarity in library we take each mob that has the required flags
- buffer the modifiedWeight with formula
- Put the mob in the single list, replace his weight inside the rarity with the modified list
This way i achieve a single list weight check without a bunch of checking rarity, then going into the rarity, checking every item for flags, summing needed weights, getting random index, returning to library and grabbing the item
You should probably reach out to the creator if you have issues with a creators code.
probably because the scripts have different namespaces. Probably need to add
using namespaceName
Its possible of course, itll just be more of a pain in the ass. What you have now is more clear and easier to follow along/debug even.
this is what i've been doing, and thanks to that i can access their scripts. but not my own. and when i try to access my own namespace, it doesn't recognize it
well, that's just the problem with the namespaces. I can't really tell you how to solve this efficiently since there are so many ways that have different comfort levels
i'll see if i can contact the guy
time to learn about asmdefs because the package/asset/whatever undoubtedly uses them 😉
thanks
that's something i haven't heard about. imma look at it. brb
pain in the ass how? 🤔
Like, to navigate you mean since its gonna be an undivided big list? I won't really need to because its just gonna be called like once per ingame day to check and spawn random mobs from the list into its spawnPoints
hello, i'm trying to make some panels on the sides of the screen that make your camera rotate (im making a stationary character), but every time i point over one of the panels it detects the left side one and rotates counter clockwise. I've made sure to have separate rotations for each of them and with a little debugging, i found that no matter which panel i hover on, it only detects the left one. I'm using ispointerovergameobject
Im honestly not fully following what you intend to do, but the current setup you have is the most clear for developers to see in inspector and actually understand. Editing it would likely also be easier.
If you're going to just take the existing separate lists and combine it into a big list through code at runtime, then theres just no point in doing this. You already have it working in a clear way, having it work with a different formula and expecting the same result doesnt solve anything new
Plus it's also just more performant to not do that
Yeah, but there is a bigger picture with generating spawner presets, their respective lists, etc. And its just costly to loop through the whole library of 1000 items in runtime, and seeing how there are like 50 spawners in the scene, its gonna freeze the game when calculating all that stuff
So im trying to get a smaller list in the spawner in editor that will allow me to lighten up the calculations on runtime
I'm not judging or anything but how accurate is that 1000 number because i feel like i've never seen any game have 100 entities share 1 spawn pool let alone 1000
well, its more close to being 120 actually, but still
You have spawner presets already dont you? Defined as a rarity, then separated into a smaller list. I dont really get what your point is here, you're saying its costly to go through a larger list but you're also wanting to combine everything into one list
How you described your current setup in the initial message is literally how you should do this.
im not combining everything in one list, im searching for suitable objects to spawn based on flags
and adding only those to the spawner list
so it won't have to go through the whole library on runtime
you should just have some sort of spawn list scriptableobject that is given to the spawners
and filter them yourself?
I feel like this whole "going through the whole library on runtime" thing was just randomly brought into context. The first message implied your spawners already had lists of what they could spawn
they have presets that have flags, and im trying to populate the spawnList of said presets based on flags through editor scripts not to handle every single preset manually
This seems like a separate problem from what you were first asking. In which case yea i think scriptable objects would be fine here to define a list that each spawner could use
yeah, that's... exactly what im trying to do but the question is not in how i should do it, its in the math
will a weight modified by a %, result in the same chance than a separate check for them
the issue is your avoiding loops for assumed optimisation problems when ideal data handling should not create lists big enough to come close to being problematic
I think you're really jumping all over the place here. The way you described you're doing the math in the first place is how you do it.
And I answered this above, the formula you showed would imply everything is in one big list. Each spawner should have not just one list if you intend to have multiple rarities
Let them choose a rarity and only have objects of that rarity type
i feel like im really just going insane by now ngl
could you give an example of those flags
i'll provide screenshots rn since i feel like i can't word my thoughts with this
This is the structure of the main library: its a list of rarities, that have %, enum to navigate and the SO with items of said rarity
the item SO that has all the items
(and the flags)
Ok let's take a complete step back and I'll answer 2 things directly. First, the problem of these flags weren't well described but no matter what you do, at the end, each spawner should have lists of what they could spawn. Each small list is associated with a rarity
Now about the formula: a weighted random formula does not care what the scale of the numbers you use is. If you have weights of 1, 1, 1 it's the same as having weights of 2 2 2. But your initial formula doesnt guarantee a direct conversion because it uses percents and rounds to int. And the formula would imply you're putting everything in a big list for the spawner rather than multiple lists which is worse in terms of performance even.
and if the editor will stop freezing at compilating scripts, i'll gladly show you the spawner preset-
and this is the preset
so the bugs have flags on which they can spawn, so does the spawner preset
so... having 4 lists like this and populating them would be beneficial than having one list?
Well I'd definitely try not to hardcode it like that, maybe have a class that stores an enum for the rarity and then list<bug>. Then you could make a list of this new class
i mean, yeah lmao, this is just a very shitty example
Or you could have a dictionary, but they arent serializable by default so youd need to look online for an implementation of that
yeah, i thought of that but i'd much rather do lists and SOs
If you're just searching for the list by its rarity, a dictionary makes more sense. Either way it could be in an SO
Still list of lists, or dictionary with <enum, list> is still better than 1 big list
ok, got it
thank you i feel dumb 😭
i've been thwacking my head at the game design behind all this for past two days with a 3 dimensional system with time & weather conditions and rarities and when it came to code i guess i'm just completely exhausted and braindead
This is also a pretty common thing for games where they will roll a rarity and then roll the actual item. Or they separate items into "tables" if rarity doesnt apply
To be fair, the whole time I was basically telling you that what you had is fine. It's just a matter of overthinking putting it into one list
One kind of thing that you don't have to act on at all and just might be worth thinking about is a lot of these spawn conditions could be defined just be the context of what the spawner is and/or where it is
eg. you don't necessarily need to know that a butterfly can't spawn at a river if you just don't ever have butterflies in a river spawn pool
i mean, yeah, but its just more things to do by hand and i want it to eco my time in the future rather than doing every spawn list for every spawner by hand and all that... seems like a tech artists' hell
👍
this way i just slap a preset, press a button and whapow it has all the right bugs
so yeah
thank you everyone 🙏
ok, yeah, this is much easier to work with
I hope there are no bugs in that code 😆
Hey, I made a gameobject with a script and the Update method only run once at the start, any idea why? Here's the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(Animator))]
public class FadeAnimationScript : MonoBehaviour
{
[SerializeField] Animator animator;
[SerializeField] CanvasGroup group;
void Start(){
}
void Update(){
Debug.Log("Script running");
if (animator.GetCurrentAnimatorStateInfo(0).IsName("FadeOut"))
{
Debug.Log("Fade Out");
if(group.alpha == 0) gameObject.SetActive(false);
}
else if (animator.GetCurrentAnimatorStateInfo(0).IsName("Idle"))
{
Debug.Log("Idle");
if(group.alpha != 1){
group.alpha = 1;
}
}
else if (animator.GetCurrentAnimatorStateInfo(0).IsName("FadeIn"))
{
group.alpha = 1;
Debug.Log("Fade In");
}
}
}
And here's what the inspector looks like:
I onky get "Script running" once in the console
And the GameObject is still active
Script too
can i see the log?
Yeah sure
It also looks like there's some problem because resizing the game's window when in play mode doesn't update canvas element's positions unless I update something in the inspector
(switching off a component or switching the GameObject to inactive and then putting it back)
Wait no that's not the only problem
The game only run the first frame
It worked just fine yesterday
i dont have enough information to conclude anything so it's kinda weird
only thing i can think of is something is disable it right after it's run once
or it run once then stopped/ disabled it self
But that doesn't solve the problem, it only updates canvas elements's positions
if(group.alpha == 0) gameObject.SetActive(false);
this one
this one causing the problem
No it's not
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(Animator))]
public class FadeAnimationScript : MonoBehaviour
{
[SerializeField] Animator animator;
[SerializeField] CanvasGroup group;
void Start(){
}
void Update(){
Debug.Log("Script running");
if (animator.GetCurrentAnimatorStateInfo(0).IsName("FadeOut"))
{
Debug.Log("Fade Out");
if(group.alpha == 0) //gameObject.SetActive(false);
}
else if (animator.GetCurrentAnimatorStateInfo(0).IsName("Idle"))
{
Debug.Log("Idle");
if(group.alpha != 1){
group.alpha = 1;
}
}
else if (animator.GetCurrentAnimatorStateInfo(0).IsName("FadeIn"))
{
group.alpha = 1;
Debug.Log("Fade In");
}
}
}
try this again the update should running and not stopping
GameObject is still active + it's not running FadeOut animation at the start, it only run it when I click some buttons but those buttons just won't appear as they don't fade in at the start
Update isn't being called in any of my script
Not a single one
I restarted the editor 5 times, didn't solve it
The component needs to be enabled as well as it's game object (and parents)
Have you used a debugger to verify it's not executing?
Yeah
Not a single one of my Update() methods are being called
this code has a syntax error, it will not work
LMAOOOO
I was like "there aren't, it works- oooohhh" XDD
I had those before, it's because it's trying to access the activity in some script, but it never prevented Update() methods to run in all of my scripts
i check his project, the update literally doesnt work and his intellisense doesnt work aswell
so until the intellisense work again i have no idea what cause it
and his intellisense doesnt work
ok, @mossy oyster you need to configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
this alone doesnt work, you need netcore and netframework 4.7.2 for it to work
speak on my exprience
with vscode anyway
with vscode they're downloaded automatically
nah fam they're not
you use installer no?
there's a .NET Install Tool
maybe i use the zip version stuff is dif
ive never installed dotnet myself
well until the intellisense is working no one know what cause it
i even tell him make blank test and it doesnt work aswell
omegalul
(which is part of c# dev kit, which the guide tells you to install)
configuring your ide is a requirement for getting help here
It's working now
nice
Looks like it wasn't set up inside of Unity
Game still doesn't call Update methods tho
ok anyways back to the issue
from this, make sure you have saved, recompiled, added the script to an active gameobject in the scene before hitting play
ok so it does work
And that's the same for every script
Not a single one of my Update() methods are being called
so this was false
lol
not being called at all and being called once are possibly different issues
make sure to be specific when describing your issue
lol i look at it and i just assume he toggle it off
Ok, I'll know it for the next time I need help, thanks
i mean, not really? the error won't be buried since it's paused
sure, but pause on error doesn't make it harder, generally
i like my log scream at me 😄
That's one of my errors tho, I can't remove it
adb is for android debugging
have you tried googling that error at all?
quick google gave this thread:
https://discussions.unity.com/t/commandinvokationfailure-unity-remote-requirements-check-failed/243031
anyone know a way to make system.speech work? im trying to do tts so unity's windows.speech wont work
hey, im trying to get unity for 3ds to work, it builds okay and i have a basic scene with some testing text, but when i run it on hardware or in citra it just crashes after a second or two.. any common issues i can check for?
sorry i know this is quite a niche unity build
is there a specific community for 3ds development? if anyone knows please share :)
Usually the game crashes when an endless loop occurs, because app is not responding or it runs out of resources. Endless loop usually happen when:
a) the exit condition of one of yours for or while loop never is fulfilled
b) one or more methods invoke each other
You can also try to narrow the problem down by checking out the game's log files:
https://docs.unity3d.com/6000.0/Documentation/Manual/log-files.html
Do you have a crash dump or any information? A crash can happen for many reasons. Post info here if you have it
Hello! not sure if this is the best channel for this, please let me know if I should go to beginner or advanced. this is my first time in this server!
anywho: I would really appreciate if i could get some help on this part of my project. I was following a tutorial which I will link here: https://www.youtube.com/watch?v=fApXEL0xsx4 I understand tutorials aren't the best way to learn, however this video uses the old input system and i wish to use the new system. so there is already a challenge for me to figure out. However I cannot replicate what is done in the video. I took 2 solid attempts at it, and the first time: my mesh was getting stretched when I picked it up. and the next time I tried it, it shot up into the air, and since the script disables gravity, it stays off for some reason and keeps flying upward lol. and after trying to fix that, it just kind of just jitters. I'll send a clip if I can.
The creator of the video kindly offered to help me, but YouTube understandably flagged my comment containing my code(but other comments have their code so its also odd). but YouTube seems to have shadow banned me from the channel for that. and I can no longer get in contact. They even removed my original comment:(
My goal at this point is to just get it to work with the old system before I even try adding the new system to it. which may be a strange approach but I don't really know a lot about what I'm doing. I feel like I have an understanding for some parts. but others I really just need the helping hand for. Which I understand, this is tricky to do alone. Any help is greatly appreciated. I have also provided my code here: https://paste.mod.gg/hkeredlddbpf/1
I have attempted other guides too, no luck, and at the end of the day: I really want to use this system, It appeals to me the most. So I would love to make this or something just like it functional.
Thank you all so much in advance! this means so much to me finding this community here. I felt so doomed lol!
In this video, I’ll show you how to pick up and throw objects in Unity 6 using a very flexible and efficient method! This is an upgrade from the tutorial I made six years ago, which is now obsolete with the latest Unity updates. Whether you're building a puzzle game or just want to add some fun carrying abilities, this video has you covered.
B...
A tool for sharing your source code with the world!
You listed a whole bunch of different issues here, you should focus on one thing at a time.
Off the top of my head the mesh stretching issue comes from if you set it as the child of a non-uniformly scaled object. The solution is to never have any object that has children be scaled non Uniformly
Im no longer experiencing the mesh stretching. I was just trying to highlight the inconsistency of the behavior. Would I be able t to share a clip of whats currently occuring?
guys what's the best way in terms of organization and practicality for autosaving a big amount of player data?
Multiple characters will be playable so I'll have general data that covers the whole save file and specific data for each character
Hi, can someone help me? I have a question.
Problem also persists with a default cube with basic box collider, rb, and no children
Don't ask to ask, just ask :)
ok sorry
Why don't I have the Rigidbody variable? I don't understand? The code is normally correct.
Separating it into small pieces that are useful individually. E.g. instead of saving data about all characters in one place you can separate it, so you can save and load only data of characters that were selected to use. If the amount of total data is huge (e.g., multiplayer games with thousands of accounts) it's worth using a system that is optimized for it (e.g., databases). Keep in mind, that splitting data into too many files might backfire - there is an overhead for each file, such as checking access privileges.
you haven't saved the file
This dot tells that your file isn't saved.
how do we do it?
also configure your !ide 👇
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
ctrl+s
thank
same as any other program/file
Ctrl+S or File->Save
my game is single player in overall (It's story rpg, and maybe I'll make it duo but not for now) with some online features like pvp. Most of the general data will be like, if you've completed x mission. What do you think?
Which problem
the object jitters instead of picking up and follwing the camera like the tutorial shows. can I send a clip?
This is what's currently happening. with identical code as the video shows.
It doesn't sound like a huge amount of data. For me small amount of data would take less than 200KB, a medium one up to 1MB, a big one up to 10 MB. The Android limit for save files is 3MB. Assuming you won't have a lot of missions and other types of data, then you will probably fit below 500KB. I wouldn't worry about it much unless you very often autosave the game or you keep a lot of saves at once. 1KB is 1K characters, so you can estimate how much data it will take. Technically you can optimize saves by creating your own binary serializer/deserializer, but it takes effort to update. Using Json format will be more comfortable (it's easier to automate, it's easy to read and edit, and it's less vulnerable to changes in code).
Btw, it's worth to mention that the most issues with save files relate to the version compatibility (e.g. when you add something new to the game, your old save files won't contain information about it). When adding new content, you should assume that your old save files may lack some information or have redundant information.
Also it's worth separating persistent data (e.g. settings) from the playthrough data (the first one shouldn't be affected by things like starting a new game or creating a new profile).
well, deepseek told me to save the stuff locally with json as u just said, and synchronize it in cloud to use the data for online features. Ty for the tips
Cloud saves are the standard nowadays. Games usually support both local saves and cloud saves.
public class ObjectMarker
{
public static List<ObjectMarker> aliveMarkers = new();
private static Sprite markerSprite;
private Image marker;
private Transform toFollow;
public ObjectMarker(Transform toFollow)
{
if (markerSprite == null)
{
Texture2D white = Texture2D.whiteTexture;
markerSprite = Sprite.Create(white, new Rect(0f, 0f, white.width, white.height), Vector2.one * 0.5f, 100f);
}
this.toFollow = toFollow;
GameObject imageHost = new GameObject("Marker - " + toFollow.name);
marker = imageHost.AddComponent<Image>();
marker.sprite = markerSprite;
marker.rectTransform.pivot = Vector2.one * 0.5f;
marker.transform.localScale *= 0.25f;
marker.transform.SetParent(HUD.instance.transform.Find("HUD Canvas"), false);
Main.OnUpdate += OnUpdate;
aliveMarkers.Add(this);
}
private void OnUpdate()
{
Vector3 screenPosition = Camera.main.WorldToScreenPoint(toFollow.position);
/* screenPosition.x = Mathf.Clamp(screenPosition.x, 0, Screen.width);
screenPosition.y = Mathf.Clamp(screenPosition.y, 0, Screen.height);*/
marker.rectTransform.position = screenPosition;
}
private void Kill()
{
Main.OnUpdate -= OnUpdate;
GameObject.Destroy(marker.gameObject);
}
}
Why is my object marker dysfunctional?
Oh god I didn't realise how big it was sorry for covering the screen
Looked a lot smaller in VS
To be more specific the world to screen point seems to mess up a bit. The markers either aren't visible or are moving to thin air
Ah I didn't know WorldToScreenPoint was in pixels
Still doesn't solve my issue unfortunately. Would this be more suitable in #📲┃ui-ux?
- not a code question
- is the message not self explanatory?
why would you need to post it somewhere else? did you not read the words on your screen?
sorry i'm debil
I have a prefab in a scroll rect with a content size fitter applied on the Content parent. I want to be able to drag the item from the scroll rect into another point in the scene. (See image 3)
However, I want the initial object in the scroll rect to stay in place as a form of infinite source (akin to Little Alchemy), so I want to instantiate another prefab with slightly different logic. I am using the onBeginDrag, onDrag and onEndDrag function to drag the object.
It all works well up to the point of instantiating the prefab. When I click on the prefab, it instantiates. However, it doesn't trigger the OnDrag event on the newly instantiated prefab. When I try to pass the EventData from the Scroll rect prefab to the newly instantiated prefab (see image 1), it still does not work. In other words, forcing it to activate OnBeginDrag does not work. I have been stuck with this problem for the whole week and I am wondering if any of you could help.
Note: DragDrop script (image2) Is only on the instantiated prefab. The OnEmotionInvClick (image1) is only on the scroll rect prefab.
Why doesn't Vector2 work?
"error describing issue"
why no work?
I didn't understand
what is not clear about the information provided
Well, I can't figure out how to solve the problem.
the computer doesn't know which Vector2 you want to use, because there are multiple possibilities
okay, did you actually read the information on the page? it explains the issue and what causes it, from that information you can easily fix it
ok how do I choose my Vector2?
if only there were a page with information about how to fix that
Resolution part tells you
ok
you have brought Vector2 from UnityEngine and System.
How do you delete a namespace?
the same way you delete any text in a text editor
It's because it's managed externally by BaseInputModule (or a class that derives from it). That script hasn't registered the new object as dragged. I wasn't investigating this script much, but it feels like it would take a lot of trouble to make it to work externally. I suggest you one of these:
a) Start Coroutine (or any other similar feature) in your OnBeginDrag method and every frame do whatever you would want to normally do in OnDrag method, then delete OnDragMethod. Also stop the Coroutine once you release the pointer.
b) Similar solution, but do it in Update instead of coroutines. Create a bool that stores the information about object being dragged, and check the value inside of Update method.