#archived-code-general
1 messages · Page 75 of 1
example
i send this to the GameData dictionary like this
SurvivorData data = new SurvivorData();
public List<Survivor> survivors => data.survivors;
public List<Survivor> FreeSurvivors => data.FreeSurvivors;
void WriteToSave() => DataManager.SaveData(DataType.survivor, data);```
it will always save multiple objects tho? i guess that's what you've meant
but not multiple objects of multiple types
Looks like you are reinventing what a database is
It's a local savegame file 
pretty much needs to work like one in my head
I‘d use a local single file database then
it's what it's doing tho
But SaveData is generic since idk what type of data i'm getting, it can be Survivor, Inventory, Shelter, City, idk..
that's why it's generic
That’s why I said you are reinventing the wheel in a worse way (from the looks)
but the dictionary collects those and saves them
so i guess it does handle multiple ones?
idk how i could make it better tbh
but it is still one file per type, not multi object multi type
hm
1 gameData has a dictionary with 1 key that equals 1 object
another key can be a totally different object
With SQLite for example
isn't that handling multiple objects 
don't wanna use SQL tbh the point is having an obfuscated file
SQLite, with Unity, dont make me laugh
plus JSON is easier like 
But does it make sense what i've said?
i mean in my head it can handle multiple types
check this out, https://stevesmith.software/save4unity.html Coming to the asset store soon
but aren't you making multiple Save files and then combining them in a single one?
no
hm then?
one save file, containing anything you want
but that's what mine is doing? 😅
1 Save file is handling multi-type, if i'm not wrong, SurvivorData and InventoryData aren't the same right?
no it's not, you have one call to save, which means you have one class defining everything you want to save
hm
your code cannot call Save twice on the same file
how so? sorry i'm kinda slow cuz i didn't sleep much today
you have no append, no indexing, no file descriptors
I mean, pulling individual objects out of the save file
you can tho
wait let me show you how the save looks
{
"_saveData": {
"0": {
"$type": "Core.Data.SurvivorData, Assembly-CSharp",
"survivors": [
{
"movespeed": 20.0,
"isBusy": false,
"isInShelter": false,
"name": "Donald Hall"
},
{
"movespeed": 20.0,
"isBusy": false,
"isInShelter": false,
"name": "Kathleen Lewis"
},
{
"movespeed": 20.0,
"isBusy": false,
"isInShelter": false,
"name": "Thomas Jackson"
}
],
"FreeSurvivors": []
}
}
}```
it will take the 0 out which is all the survivors and free survivors out of the list
1 would contain inventory
2 shelter / city etc etc
no, you have to load all of them in order to be able to access any one of them. If I want, only e,g, survivors number 1 then you cannot do it
i mean, SurvivorData is a list, and i really won't care much with the individual aspect of 1 survivor
You can separate in multiple files.
at least on the game design it doesn't matter much, and from the top of my head i don't see where being able to handle 1 survivor or 1 piece of info can be necessary. (does it make sense?)
i really just want to pick up a list of x things and read and load them. But i'm always open to other POVs
exactly, you have to separate into multiple files, that is why I say this design paradigm cannot handle multi object scenarios, plus the fact that Json is just crap for games
I'm using JSON cuz it's simply faster at this point of development, plus it's nothing serious for now.
but do you think i should go for something where it can handle 1 object inside the list at the time?
It's like i've said, i don't really need to access that type of info during loading, since it's not really important hence the why i've made it this particular way
or saving 1 specific survivor
it's not about 1 object in a list, but say you have 10 lists, being able to load one of those without having to load the other 9 might be nice
i mean i only considered of doing loads during the start of the game / whenever a save is loaded
hm.. so what would you suggest? creating several variables instead of a dictionary?
where i can serialize those objects inside the save?
You need to add a structure to your save file, on top of your Json, that way you can access parts of the file without having to pay the overhead of accessing all of it
think about the way that FAT tables work on disks
trauma
but what type of structure would that be i mean, like inside the json or outside, where the json would be inserted?
Sorry, I'm not trying to be cruel, this is just the way computers actually work
i know heh, dw i actually want to make a decent save & load, the more i learn the merrier
Serialization is always traumatic
just buy mine when I publish it,leave the grief and agrivation to me
now you left me curious 
@heady iris is right, Serialization, done correctly, is not for the uniniated
one thing that can help is separating "authoring data" from "runtime data"
for example
in my soulslike I'm working on, your inventory is full of InventoryItems
these contain instructions for how to create an actual weapon you hit things with
it's like i've said, i haven't really developed many S&L systems, and the ones i've made were pretty simple compared to this one
I mean all the data i'm saving is pretty much runtime there isn't anything really authoring, at least for now. Maybe when i get to the shelter / city it may contain some type of data where that separation is needed, but ty for the tip ^^
if you are thinking about saving SO data, that is 'Authoring' either that or your design concepts are wrong
i didn't make them, but i think they are authoring yes
just peeped quickly, but yeah some parts will change during runtime but most of it is authoring
then you need https://assetstore.unity.com/packages/tools/utilities/scriptableobject-pro-218340 to do the job
so you're saying if the stuff i save from the SO changes during runtime it won't save correctly? 
correct
yes
gonna be a pain but not for me 
hmm i mean we were using SOs with some mutable variables, but i didn't even consider the save and load question at the time tbh
forget mutable variables in SO at runtime outside of the Editor, Ain't gonna work
but now you left me thinking if my S&L system is too bad in a overall, even if i don't want to access a list, but instead load everything at once every load cuz i mean that's how we were thinking of doing.
ty for the tip, i should have thought that from the beginning tbh
it's in the docs but, hey, nobody reads them anyway
i mean i knew SO act like structs but didn't even came to my mind about when reading them after their values have changed

Biggest problem is different behaviour in Editor and in Build. Bad Unity
Tbf, sometimes i wish unity would help on that end. I feel like there are some QoL things around the editor -> build that could be enhanced. But hey i ain't complaining
anyway
guess i'll work on the changes once again i appreciate for the golden nuggets you've gave me

!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
np. DM me if you need advice, Serialization/Deserialization is one of the things I like to work on most
oke will do, i appreciate it
Hello, when using assembly references in Unity, does everything have to be in a folder with an assembly reference or can i have a script in the default C-Sharp assembly? how can i make my assembly reference include the C-Sharp default assembly?
how can i make my assembly reference include the C-Sharp default assembly
You can't. Once you start using asmdefs you basically have to use them for your whole project.
Make a game assembly and have the other assembly reference it.
so you can't have a reference to the default C-Sharp assembly then
No
i see i'll add an assembly at the root of my scripts folders then
Anyone else having an issue of scripts inside Editor folders being included on build? I thought any folder called Editor wouldn't be included on build.
Shouldn't happen. Can you show an example?
C:...\Assets\Modules\Levels\Unity\Level1\Editor_Extensions\PropertyInspectors\Editor\HideInNormalInspectorDrawer.cs
That file I had to put #if UNITY_EDITOR on
Assembly definitions override Editor folders, if I remember correctly
What about this file?
So if you have one that encloses that folder
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
[CustomPropertyDrawer(typeof(HideInNormalInspectorAttribute))]
class HideInNormalInspectorDrawer : DecoratorDrawer {
public override float GetHeight() {
return 0f;
}
public override void OnGUI(Rect position) {
// do nothing to prevent the field and any custom property drawers from being displayed in the inspector
}
}
#endif
Ah yeah I do
Yeah only thing I can think of is you have an assembly definition
That is annoying
Not really
You can just set the assembly to not be included in the build
I can see it being useful, but annoying that it isn't clear that happens
If you are mixing editor and non editor stuff in one assembly you will need to split it up though
I mean, or just compiler directive it
That's wasteful though...
Why include files in your build that have no business being there
A few clicks in the editor > writing a bunch of preprocessor directives in many files
If I have a larger number of files I would agree, but it is just that one currently.
Though also I have some functionality that can use Undo in editor(or just normal in build) so having a version of each makes sense, and then already have functionality specific to different platforms anyways.
hi
public class spawnRes : MonoBehaviourPunCallbacks
{
if (PhotonNetwork.LocalPlayer.ActorNumber == 1)
{
GameObject sco = PhotonNetwork.Instantiate(Score.name,new Vector3(0f,0f,0f),Quaternion.identity);
GameObject go = PhotonNetwork.Instantiate(Dice.name,new Vector3(0f,650f,0f),Quaternion.identity);
sco.transform.SetParent(Canvas.transform, false);
go.transform.SetParent(Canvas.transform, false);
}
else
{
GameObject sco = PhotonNetwork.Instantiate(Score.name,new Vector3(100f,0f,0f),Quaternion.identity);
GameObject go = PhotonNetwork.Instantiate(Dice.name,new Vector3(0f,650f,0f),Quaternion.identity);
sco.transform.SetParent(Canvas.transform, false);
go.transform.SetParent(Canvas.transform, false);
}
}```
when two players are joining. they can only see their own instantiated objects
and cant see each others
what is the problem?
i have added a photon view component along with a photon transform view component to the prefabs of the instantiated objects
Probably worth asking in #archived-networking
oh ok
But check if your Instantiate method here can take a parent Transform directly. It's never good to instantiate an object in world space and then parent it to UI. It messes with the RectTransform
It might not solve your issue, but it's a step forward to better object management
Regular Instantiate has a version where you can pass a Transform directly to it, aside the position and rotation
Instantiate(prefab, pos, rot, parent)
So check if your networking one can do that too
hey um,
ive got a question.
i have two gameobjects, and one of them HAS to be initialized before the other.
i mean the gameobjects themself tho.
Make a script that spawns one then the other
Or have the first one spawn the second one
Also you didn't actually ask a question 😂
hey guys i have a projectile which spawns an explosion particle system after it enters a collision. the issue is this explosion particle stays at the same place and doesnt happpen where the projectile has collided
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
here is the projectile code
here is the projectile hierarchy
GameObject ps = Instantiate(explosionParticleSystem.gameObject)
You're not even attempting to set the position 🤔
Also you don't need the .gameObject there
are awake and start called when a scene is loaded as additive?
but i put Debug.Log in a object, and it didnt show...
only when i load the scene directly.
where is the log, is the object enabled?
never mind, it was filled with audio listener msgs so i didnt see...
I tried this script to download a pdf file from the given url. It works on PC but not on android. Pls help!
Can someone help me out? :(. I'm trying to get the forward bounds of my collider in world space. In particular I need the center bottom forward. I marked with a red dot the position I'm aiming to get. I can't quite figure it out since bounds has size and center.. But doesn't translate from local to world etc.
find the point in local space, then transform it to world space
I would do something like...
Ray r = default;
r.origin = transform.TransformPoint(Vector3.forward * 100);
r.direction = -tranaform.forward;
if(myCollider.Raycast(r, etc...)) {
var point = hit.point;
}```
but yeah, I'd just do transform.TransformPoint(collider.center + Vector3.Forward * collider.bounds.z)
i forget if bounds is half-width or full-width
if it's full-width, divide by 2
The bounds aren't quite the actual collider shape though
You can also just make a child object at the point you want
And use that position
someone help me fix this bug, because I'm trying to make the button turn on application from game files but something didn't work, because it can see the file but won't turn it on something
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;
public class UEChanger : MonoBehaviour
{
string m_Path;
public void ChangerToUnrealEngine()
{
m_Path = Application.dataPath; Process.Start("/Ognaria_Data/Resources/UnrealEngineSource/WindowsNoEditor/Ognaria.exe");
}
}
how does adding/removing/renaming fields work with BinaryFormatter? Does it stop working? do they get deserialized as a default value?
You really shouldn't use BinaryFormatter...
why not?
what about xml?
or json?
but those dont have references right?
how do i handle versioning with serialization? What should I use to serialize/deserialize?
does the using directive import the entire library ?
Im asking because what if i only want one class from the library do i have to drag in everything else as well?
depends on the class and the license
doesn't binaryformatter lead to code execution when deserializing malicious data
Oh because it may be refernecing other classes in the lib?
yeah, you probably can't just take the file on its own
So, what should I use?
having the whole library would increase build size, but wouldn't reduce performance (unless you are really ram limited maybe)
The compiler should be able to optimice the import of the library
pretty sure it won't unless you build for il2cpp, then it will strip
And unless you are running whatever you are making in a potato and the library is huge, it shouldn't be a concern
The java compiler optimizes it, I don't see why the .net one wouldnt
well yeah code size isnt generally an issue for Unity games
Ordinarily, the build process includes the entire assembly file, no matter how much or how little of the code in an assembly your Project uses.
No idea if that is the mono/.net default or if Unity has changed it
this is for IL2CPP
it can be used for both
oh, d'oh, you're right
That's the answer to his question, but honestly, what he should hear is very likely "don't worry, it won't matter"
ya
Is there an easy way to check if an object is a 2D Canvas object or a 3D one?
I guess I could check if the transform component is a rect transform or a Transfrom, right?
didnt know its that easy
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ResourcesManager : MonoBehaviour
{
public static ResourcesManager current;
private void Awake()
{
current = this;
}
public GameObject exampleObject;
private void Start()
{
exampleObject = Resources.Load<GameObject>("exampleObject");
}
}
is this an acceptable way for using resources folder
basically a singleton that loads them all
and other scripts get prefabs etc from that
what is the generally used method for this?
Why not just use a direct reference if you're doing this
wouldn't that require dragging them all
for each scene
oh i can use prefabs
thanks
can i do static GameObject and drag them in editor
Resources.Load can only work on prefabs already 🤔
so I'm not sure what you would have been doing before
no
static is right out for the inspector
dynamically loading assets by name
oh
honestly in serious projects, Resources.Load is not used at all, Addressables are.
Resources.Load can be useful for lazily loaded singletons and self-initializing singletons / ScriptableObjects
addressables lets u register all the existing position of the assets across the whole project file
and then by using the API, u get to spawn stuffs without assigning them on inspector
Addressables lets you reference assets without immediately loading them into memory 
it looks like the exact thing i was looking for
imagine u have 10000+ assets in ur folder, its extremely hard to find them everytime right? if u can register the stuff u want onto the addressables. You will have a simpler menu to access them
normally i wont use addressables, but my team does, even tho they use it very differently unlike the normal way
Thanks! I'll try it out.
i think one of the most important reason of ppl using addressables is the decentralization
to be honest i am just looking for a way to load objects without making everything complicated
when the project gets bigger referencing stuff becomes hell
just pack ur folder well bruh
but i guess addressables is fine if u have tons of stuff
and i still need someone to explain more bout it to me tho
i joined a team project for like 6months, and the image that addressables left me is just bad
it looks like
maybe its because how my team use it differently
sorry i was away
rather than inspector
how would i go aboout doing that?
Instantiate has overloads that take a position parameter. Check the docs:
https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
yeah just go try it
thx
im getting an error on this line:
Transform position = transform.position;
'Cannot implicitly convert type 'UnityEngine.Vector3' to UnityEngine.Transform'
transform.position is a vector3
what error
Argument 2: cannot convert from 'UnityEngine.Vector3' to 'UnityEngine.Transform'
did you save
yes
its a different error
OH DIFFERENT LINE
sorry
the line is this one
GameObject ps = Instantiate(explosionParticleSystem.gameObject, position);
can i not use vector3s for instantiate argument 2?
you need to add rotation as well
or else rn it's a Parent parameter which is only Transform
GameObject ps = Instantiate(explosionParticleSystem.gameObject, position, Quaterion.identity);
thank u!
always look into the docs when things don't make sense
https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
for passing position it is, but yeah Quaterion.identity = no rotation
there are only two overloads
Transform
Transform, Vector3, Quaternion
er
i am very wrong on that number!
there are 10, lol
GameObject , Transform
oh yeah
i forgot the gameobject
lol
but yeah, there's no overload that only takes a position
instantiate(GameObject)```
i think its same as
```cs
instantiate(GameObject,Vector3.zero,quat.identity)```
which spawn stuffs on origin
there nope
you can create one tho, even its not really necessary
public void Instantiate_PosOnly(GameObject obj, Vector3 pos){
Instantiate(obj,pos,quat.identity);
}```
when u call this function, it will act as ```cs
instantiate(GameObject,Position)```
well, if you dont mind compile errors instead of running code
you could write an extension method :p
i forget if it gets mad if you make an extension method with the same name as an existing one
no, you can overload extensions
nice
you're in a different namespace anyway
What's the difference between vector3 and float3?
float3 is used in the Mathematics package that is optimized for burst, Vector3 is the normal one used everywhere in the engine without specific optimizations
one is used in C# the other for shaders, they are both, basically the same
https://docs.unity3d.com/ScriptReference/Transform.RotateAround.html
How do I go about normalizing(?) the speed for this method? I'm trying to get a constant speed such that it travels the same distance that not dependent on the radius.
trig time! trig time!
well, sort of
A rotation of one radian around a unit circle will move you by exactly one unit
because the circle's radius is 1
diameter is 2
circumference is 2pi
and it's 2pi radians to make a full turn!
so, dividing the rotation speed by the radius will do the trick
I fell asleep in trig. Would been more exciting if I found it useful at the time.
well, you're in for a treat in game dev :p
I added the newtonsoft package, but rider isnt detecting any newtonsoft classes
any ideas about what i should look for?
you might need to regenerate the project files in the External Tools menu
how did you add the newtonsoft package?
with the package manager
can you see it in your packages folder in the project?
yes
you have added the correct using statments?
ok regenerating the project files worked
no why would I do that manually

but its working now
thanks!
When ever I try to move backwards, it spins uncontrollably.
-- the script: https://pastebin.com/RuDA4J60 --
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Ah, ok I think I've tried that before, but I assume I've more to my problem than just that. I guess the problem now is translating linear speed(?) into that rotational speed.
let's see
so your goal is to rotate at a specific linear speed?
with a known radius
Yeah, that's probably the idea
Dividing by the radius will make it so that rotating at one radian per second makes you move at one meter per second
er
that was not the correct way to say that!
lol
Hello?
if you rotate by 1/r radians per second, you will move at 1 meter per second
there we go
a minute, please :p
so, to move at x meters per second, rotate by x/r radians per second
I was just seeing if you would notice me, I'll wait, thanks!
So, x in this case would be speed * Time.deltaTime or is there more to this? At the moment it's much, much slower with that than a linear projectile
yes, you'd multiply deltaTime in afterwards
So what are you trying to do exactly?
Angular to linear velocity I would assume
Angular is at an angle, so you would try to convert it to a linear line-like velocity?
if you rotate with a radius of 1 at 1 radian per second, the object should appear to be moving at 1 meter per second
is it appearing much slower than that?
transform.RotateAround(sourceSpawnPosition, transform.up, ability.StatDict[AbilityStatType.AbilitySpeed]/ability.StorableSO.DistanceOffset * Time.deltaTime);```
does travel much slower than my normal fireball of ability.StatDict[AbilityStatType.AbilitySpeed] * Time.deltaTime * objectDirection;
is objectDirection normalized?
Ah, actually I don't normalize this one
that'll do it!
There's probably something I'm doing wrong beyond that, but I'll revise on what ya said
tyty
Alright, good luck!
so gideon, your character spins rapidly when you try to back up?
Yeah.
When ever I try to move backwards, it spins uncontrollably.
-- the script: https://pastebin.com/RuDA4J60 --
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I've been trying to fix it for the past 2-3 hours.
i noticed that both the horizontal and vertical movement affect the y-axis rotation
Really?
oh.
So what do I do to help with it?
well, I don't really know what your intent is here
can you explain what this is doing?
So, it's a movement script that is supposed to work with Keyboard and mouse, and controller with animations, I would of used the Input system asset, but I found it easier to do this.
so it tries to rotate you to face the direction you're moving in
although you only have the vertical component on the direction vector
Yeah, I use the Horizontal just for turning.
The video.
ah, I see
oh
one big thing...
you add the rotation of the camera to the desired rotation
so if the character rotates a bit, the camera gets rotated too, right
and now it wants to rotate even further
If the camera is always trying to stay behind the character, then it will be impossible to walk towards the camera
and you'll just spin violently
see how it behaves with a fixed camera
So, what do I do?
Yeah.
ideally, the camera shouldn't rotate when the player rotates
i'd suggest using Cinemachine for this
the Free Look Camera is a good fit
so you don't want the camera to ever rotate?
or do you want it to always be exactly behind the player
if so, then you'll need to make it so that the player doesn't rotate when moving backwards
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + Camera.main.transform.eulerAngles.y; you can probably just get rid of this entirely
How do I just make it walk backwards?
you don't have a horizontal component in there -- you do that rotation separately at the end
so all this can possibly do is try to rotate the character 180 degrees around
What do I do here: ```cs
Vector3 moveDirection = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward * Speed * Time.deltaTime;
I guess you can still compute the target angle
just don't use it to rotate the player
Ok.
One sec.
It doesn't spin, but when I go backwards, it moves forward.
Wait, let me fix something.
I have a question
I have this player script i made which is a mix of my stuff + changed carlson movement bc im lazy and other crap
but now i have this problem where it automaticly adds a character controller to the player object
and idk why
it probably has a [RequiresComponent(typeof(CharacterController))] at the top
i use a rigidbody movement so you could undrstand why this is a big problem
nope it doesnt
doesnt do that either
is the player a prefab?
i can make a pastebin of the script to show
yes
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
and how does the player get into the scene? Is it there from the start? Is it spawned?
it automaticly adds it when i reload the prefab
wdym by "reload the prefab"?
open a dif one and go back in
Check all of those scripts
when i remeove the playercontroller script it doesnt auto add the CC
its only with the PlayerController script
I'd guess it might have something to do with mirror
something about how prefabs are registered with it perhaps
Unrelated but:
float mouseX = Input.GetAxis("Mouse X") * Time.fixedDeltaTime * sens * 50f;
You can remove 50f and fixedDeltaTime here, they just cancel each other out
fixedDeltaTime is 1/50
50 * 1/50 is just 1
hahaah thank you
yes, and mouse input should not be scaled by deltaTime, anyway
it is an absolute quantity
is there a way to register prefabs with mirror or something
i don't really know how it works
i know you have to do that with Netcode for Game Objects, at least
but that's something else entirely
i go through and register all prefabs in a resources/prefabs folder
thats not the exact dir but still you get my point
i dont get how to fix this though
i would start by doing a sanity check
stick another random component on the prefab
see if that component shows up in game
ok
if it does, then it's probably not an issue with an old version of the prefab somehow getting instanced, or something
yes it does
it does*
i fixed it
let me say the solution
for furture reference or similar issues
there are examples in mirror and in those exampeles there are premade scripts in games called the same as my own script, unity got confused betweent he scripts and saw the require conponent of the Character Controller and added it to my prefab.
basicly just delete the examples and change the name of the script fixes it
how can i load an asset instantly when using addressables?
#📦┃addressables - you probably won't like the answer
didnt knew there was a channel for that
// Create a static instance of InputManager that can be accessed from other scripts
public static InputManager Instance { get; private set; }
private void Awake()
{
// If an instance of InputManager already exists, destroy this duplicate instance
if (Instance != null && Instance != this)
{
Debug.LogWarning("InputManager: Duplicate instance detected. Destroying the duplicate instance.");
Destroy(gameObject);
}
else
{
// If there is no existing instance, set this as the instance
Instance = this;
// Make sure that this object persists across scenes
DontDestroyOnLoad(gameObject);
}
}
Hello, i wanted to get some more clarification into using events. so i have this singleton class for input with the logic to set it up in the awake method, below is the code of another script that needs to subscribe to this script.
private void OnEnable()
{
InputManager.Instance.InputGearUp += OnGearUp;
InputManager.Instance.InputGearDown += OnGearDown;
}
private void OnDisable()
{
InputManager.Instance.InputGearUp -= OnGearUp;
InputManager.Instance.InputGearDown -= OnGearDown;
}
Based on the documentation i would assume that the awake method for sure is called before on enable but i get a null reference exception
or is it done like this where awake and onenable are called after each other for each object and not first all objects their awake methods and then the onenable method?
Awake will run before OnEnable on the same object
yes this
is there a reason it's done like that?
Definitely
I assume Awake -> OnEnable is just part of the initialization process for an individual script
But seeing as Unity is closed source and we're not privy to the code or the people who made it, we can only speculate
Yeah, i guess i'll use start for the subscribing then
or maybe just also do it in start
or use script execution order
yeah, but i first want to do it without any orders just changing the code
onenable is not called a lot so i will add a check for it
So I've been making some abilities that spiral out from the player and it's been working out, but I'm trying to figure out for this code:
objectDirection = targetPosition - relativeTransform.position;
objectDirection = Quaternion.Euler(0, 90, 0) * objectDirection;
objectDirection = objectDirection.normalized;
posChange = ability.StatDict[AbilityStatType.AbilitySpeed] * Time.deltaTime * objectDirection;```
Changing Eulers here to anything below 90 will spiral outward, and anything above 90 will spiral inward with the current code, but at exactly 90 I expect the projectiles to hold their position in a perfect circular motion, yet after a few rotations they do gradually fall off course.
Is there anything I'm missing here to prevent that?
it could be down to accrued error
even if it's only slightly off, the errors will pile up over time
I know there's some floating point accumulations, but it falls off so quickly.
I wonder if you could compute the position parametrically
that might be the wrong word
you'd have a function that you just plug the lifetime of the projectile into and get a position
i'm not sure what the math would look like, though
Did you forget to normalize your direction before multiplying by the euler angles?
- Move
objectDirection = objectDirection.normalized;aboveobjectDirection = Quaternion.Euler(0,90,0) * objectDirection;
Oh, also I manage to get the movearound method to work, I just had to multiply using the Rad2Degrees
object direction is initalized as vector3.forward
ah, yeah let me try that. I think I really tried everything like that so far
hm, that could cause some errors, yeah
Really it's closer to 89 degrees that really keeps it from going astray
Quaternion.AngleAxis(90, Vector3.up); behaves similar
You might have to perform some rounding logic to see if you are within 90 degree.
Otherwise, comparing exactly by precision value is unpredictable.
Are you calling this inside FixedUpdate()?
Update
oh! that's a good point
Try FixedUpdate() - Consider precaching Quaternion.Euler(0,90,0) since the value is immutable. No need to call it every update. 😄
private static Quaternion kCornerAngle = Quaternion.Euler(0,90,0);
yeah ive got it cached, just typed what I'm doing ;p
Wait... untested code, not sure if I can call method inside static variable.
you can in that case
I think Update would be fine since you want to refresh position by frame dependent... Still, I think the problem is that you're going to be running into precision problem before your projectile could ever be perfect.
MoveAround?
RotateAround*
ah
RotateAround should just be doing trig
whilst you're moving the object in straight lines
now, in theory, those should be the same thing..
var lookDir = Vector3.Cross(targetPosition - transform.position, Vector3.up);
transform.RotateAround(
sourceSpawnPosition,
transform.up,
Mathf.Rad2Deg * (speed / (ability.StorableSO.DistanceOffset / 2)) * Time.deltaTime);
transform.rotation = Quaternion.LookRotation(lookDir, Vector3.up);```
works fine
I just kinda want the other thing to work with the spirals and the circular motion, but if it's just a precision thing then I guess it's not that big of a deal (don't want to deal with that right now)
Only problem is the look direction with this method is a little funky because by default it looks at the object it's rotating around
yeah, it's annoying to have to have a special case
How are you making it orbit nearly 90 degree? What govern's the velocity?
speed * Time.deltaTime * objectDirection
If you are controlling the vector, try considering adding weights to ensure the object will orbit perfectly, You can disable this feature by multiplying by magnitude value.
what?
I'll probably load up a blank project and play around with it more in case I've some hiccups somewhere in the code.
The SO page I mostly got the info from didn't really mention it working perfectly at 90, I'm just curious as to why it's not
So i have the strangest bug happening to me right now.
I have a script with the OnDrawGizmosSelected() function defined.
Now, this does not work unless i go into the gizmos and tick the specific script first off and then on again.
And then it works for all of the gameobjects which has this script attached, but as soon as i switch to a gameobject, still with the same script attached, that is a child of another object then the gameobject i had selected when i turned the gizmo off and on again it stops working.
oh hang on a minute
do i need both
OnDrawGizmos()
AND
OnDrawGizmosSelected()
in my script for the selected version to work? o.O
the component has to be exapended
and the object has to be selected
if you only want it for selected OnDrawGizmos is not needed
exapended?
if the component that has the OnDrawGizmosSelected on it in the inspector is not expanded out so you can see everything it will not display
ah, well i tried that, didnt do anything really.
But adding OnDrawGismoz() in the script, just empty, worked
weird what is the logic
sounds like it could be a bug, might see if there is a new minor update for your unity version
Your component must be fully expanded for OnDrawGizmos()/OnDrawGizmosSelected() to work. Are you sure that's how you spell your method?
This is a much better way of doing it. Line renderer just isn't made for complex UI things.
✅ Series Playlist: https://www.youtube.com/playlist?list=PLzDRvYVwl53v5ur4GluoabyckImZz3TVQ
Grab the Project files and Utilities at https://unitycodemonkey.com/video.php?v=CmU5-v-v1Qo
In this video we're going to create a graph in Unity.
You can use this to display information in your game like amount of money earned per hour or guests visited p...
I hated how there isn't a UI Line Renderer 😦
Nope
hi, i have a question
I am trying to create a hud using ui toolkit
I created a text label, but I am not sure how to access it in my script
Looking for the best approach.
I have a quest system, one of the goals is to talk to an NPC. I listen for the NPCInteractEvent to achieve this but how I implement it has a side effect. The interaction event is fired before I deal with the dialogue then I check the goals status so I can display relevant dialogue but of course, side effect, quest gets completed before the goal check.
How would it be better to handle this? For added context, dialogue is handled via nodes. In a sense, the event would be better fired after interaction has finished but that may not always be applicable. Maybe there should be two events (interact start and end)? I'm not sure.
Maybe a dialogue completion should be a separate event entirely?
Only completing quests on interaction sounds very limited.
mmm actually true, it prevents dialogue where one option progresses to the next goal and the other doesn't.
although that may be better handled in the node graph for said npc or what have you, not too sure but you're right
Hello everyone,
I'm having some trouble with my Scriptable Object in Unity. I'm trying to use it to store data for my game, whenever I enter play mode or restart Unity, the data is lost.
I am trying to create a Scriptable Object that allows me to easily specify the boundary rules for a procedural generation project. Here are my two scripts: the main script and the editor.
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
[CreateAssetMenu(fileName = "New Prototype", menuName = "Prototype")]
public class Prototype : ScriptableObject
{
public Tile tile;
private Dictionary<int, bool[]> connections = new Dictionary<int, bool[]>();
public bool[] GetConnections(int id)
{
if (!connections.ContainsKey(id))
{
connections[id] = new bool[4];
}
return connections[id];
}
}
using System.Linq;
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(Prototype))]
public class PrototypeEditor : Editor
{
private Prototype prototype;
private void OnEnable()
{
prototype = (Prototype) target;
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
Prototype[] prototypes = AssetDatabase.FindAssets("t:Prototype")
.Select(guid => AssetDatabase.LoadAssetAtPath<Prototype>(AssetDatabase.GUIDToAssetPath(guid)))
.ToArray();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("", GUILayout.Width(EditorGUIUtility.labelWidth - 4f));
EditorGUILayout.LabelField("Right", GUILayout.Width(40f));
EditorGUILayout.LabelField("Left", GUILayout.Width(40f));
EditorGUILayout.LabelField("Up", GUILayout.Width(40f));
EditorGUILayout.LabelField("Down", GUILayout.Width(40f));
EditorGUILayout.EndHorizontal();
foreach (var p in prototypes)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(p.name, GUILayout.Width(EditorGUIUtility.labelWidth - 4f));
bool[] connections = prototype.GetConnections(p.GetInstanceID());
connections[0] = EditorGUILayout.Toggle(connections[0], GUILayout.Width(40f));
connections[1] = EditorGUILayout.Toggle(connections[1], GUILayout.Width(40f));
connections[2] = EditorGUILayout.Toggle(connections[2], GUILayout.Width(40f));
connections[3] = EditorGUILayout.Toggle(connections[3], GUILayout.Width(40f));
EditorGUILayout.EndHorizontal();
}
}
This results in the desired setup seen below.
I am able to check the boxes and see the updates, but the data is lost if I enter play mode or restart unity.
I've tried calling AssetDatabase.SaveAssets(), SetDirty(), and trying various methods to serialize the data, but nothing is working.
Does anyone know how I can fix this issue? Any help would be greatly appreciated.
Is there a way to correctly add a component using OnValidate? It's working but I'm getting this warning: SendMessage cannot be called during Awake, CheckConsistency, or OnValidate (GameObject: OnDidAddComponent)
Hoping to avoid a custom inspector
Hmm, looks like you can use async await to get around it
I'm trying to use
[Preserve]
to prevent reflection code from stripping but it is not working
all the reflection code seems to be still "missing" after the android build
it's IL2CPP
I'm not sure reflection works in IL2CPP builds.
Since it's part of the .net runtime afaik.
According to the docs some of it works.🤔
I guess it needs to be checked on case by case basis.
Not really, that way is difficult to customize, overly complex and built from scratch. My workaround way is easily customizable and uses built in features rather than writing a line render engine from scratch.
Plus I highly doubt that it would work overtop of a 3d camera which is the whole reason for a workaround anyway.
He seems to be making it for 2d, or for 3d use but on a separate camera which wouldn't work for me.
if(deadBodies.Count >= maxDeadBodyCount)
{
for (int i = 0; i < batchRemoveCount; i++)
{
deadBodies.Remove(deadBodies[i].gameObject);
}
}
Would Running this statement in Update be a heavy task? I am unsure how fast Lists are
It’s won’t be heavy until the actual removal occurs. You should use a queue rather than a list
ill look into those rn
for (int i = 0; i < batchRemoveCount; i++)
{
deadBodies.Dequeue();
}
Does this look right?
Since: "Returns an item from the beginning of the queue and removes it from the queue."
yep
Alright great, I cant see Queues in the inspector sadly though
I wish it worked with more data structures
Hi
any Visual Studios user here?
this is very useful extension for you if you use Visual studios
I hope its Helpful
@buoyant crane I cannot seem to get game objects from the Queue, cannot find much on google, I may need to just use Lists? (I need to destroy gameobjects from that queue)
When you call Dequeue it returns the GameObject as well
So you could do Destroy(bodies.Dequeue());
Bruh I tried that the first time and it didnt work, now it does lol
Thanks
Once again
Now I can happily remove dead bodies
well of course it works, otherwise there won't be any Google Play anymore
it's just when you strip code at the highest level, it will be gone
What's usually the more performative way to prevent multiple instances of damage to an entity in a time frame? Having a lookup table with IDs and with a previous time is the easy solution, but let's think about hordes of enemies where you've multiple abilities at your disposal.
Is it really a performance problem?
Have you benchmarked your current implementation and seen it be an actual problem?
I've yet to really benchmark what I've got to the fullest, but this is more of a general question for its implementation. At the moment each of my abilities does contain a hashset which keeps track of previous hit enemies, but I'm getting to the point where I'm slinging many of those abilities all at once into waves of enemies.
Even if theres 1000 enemies, keeping track of them is nothing
A hash table lookup is one of the cheapest ways to do this kind of tracking
how can I spawn objects randomly around the scene? I don't want them to spawn inside other objects
pick random position and spawn
yeah but how do I make sure it doesn't spawn in other objects?
something like physics.checkbox ?
if blocked , spawn elsewhere
ok thank you
Unity does not serialize dictionary which is why the values are lost whenever you quit the application.
hello
i have a Country class and a Tile class
there's going to be a static array/class of Tile instances
and a static array/class of Country instances
now i want each tile to store which country it belongs to
and each country to store a list of tiles it has
usually i use pointers, but this is C#
any ideas?
references wont work
public class Tile
{
public int x;
public int y;
public Biome biome;
public Country* country; // cant do this
}```
also, in the future i want to have a function that would look kind of like this: ```CS
public void DrawName(List<Tile*>, string name);
it also has pointers
It's not really recommended to use pointers in C#, but if you really want to I suggest reading this for a bit:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/unsafe-code
ah, thanks
there's no way that the pointer will be used after dereferenced btw (it's a pointer to member of static class)
oh, if Country is a managed type
what do i do?
Classes are reference types in C#, there is no need for a pointer
wait really?
i'm pretty used to C and C++(was working on something else) so it's pretty confusing
Classes are reference types, structs are value types. Classes are allocated on the heap, and structs are allocated on the stack if they're defined in a small enough scope that allows for it
that's awesome
thanks
way easier now
wait, what about if you make an instance of a class locally
and then you call a method with it, then the method stores it somewhere else
the class wont be dereferenced right? because it's on the heap
so it's safe
won't, and that's the whole point of a managed language like C# comparing to unmanaged ones like c, cpp,
so it's forced you have to use "new" to create class instance in C#,
downside is due to this nature, you cannot have const correctness in C#
If anything references the class it will not be deallocated
You also have to mind clearing references to avoid leaks, which can be tricky at times with stuff like closures
i really wonder can you somehow impl const correctness in C# tho

i miss that thing so much
but then again, that's like just against the whole point of C#
idk
Anyone know how to make a Pathfinding Agent with Aron's A* Pathfinding stop getting stuck at corners? I am just at a lost.
This is on a 2D Tilemap
I'm guessing the problem is with how you move the agent, rather than with how the path is calculated (A*)
I just have A* move the agent for me, I guess? Default settings, except for Pick Next Waypoint Dist which was lowered due to the Agent trying to go through walls.
so i have to make a change to my project so that all things that have sprite renderers in my project have to have them be a separate child game object from the parent object and i have to change all the animations so that they are on the right sprite renderer. Is there a quicker way to do this because it's becoming very tedious
You can edit the path for an animation channel directly. That might help if you’re making the same change for every single channel
I’ve done that for my VRC avatar when moving parts around
how would you do that
so I made an animation that controls the scale of the "Path" object
if I hit Enter (on macos; it's probably F2 on windows), I can edit the target of that channel
How can I play an audio file from disk? All google posts I've found point to a WWW class which is deprecated.
UnityWebRequestMultiMedia
for URI do I pass in the raw filepath or do i need to add something else?
I would expect to need to use the file:// protocol
thanks
but this is spitballing :p
Just 3 months ago I created a game using Unity Mediation package and got a good grasp of how to write code. Now I wrote similar code for my new project just to find out that Unity swapped that Mediation package with some LevelPlay that works with IronSource.
Why does this change so often and should I expect LevelPlay to change again anytime soon?
The inputs in the new input system, what are their refresh rate? (Such as when using Pass-Through and ReadValue<>)
Would ReadValue return the last input registered from the hardware polling rate, the input from the last frame update, or from the last physics update?
Ah, thank you, don't know why I couldn't find that
Hey, i want to draw a minimap of my game. Basically i just want to draw some rectangles and layout of the map.
I am thinking of using Texture2D .. however this is reaally slow, i want to avoid drawing every pixel ( especially wasting CPU filling all the image with transparent pixels).
Is there a better way ?
Typical approach to a minimap is a camera rendering to a RenderTexture, drawn in the UI with RawImage
is it possible to make a button do something different on rclick rather than normal click
yep
how
Use IPointerClickHandler instead of the button on click
or event trigger
and the pointer event data contains info about which button it was
ya i saw that, i dont want to do it because i want my map to be transparent over the screen ( like diablo 1)
uuuuuuuuuuuuuuugh Im too tired to learn something new haha
Imma make a smaller button for dropping
sorry
ill get back to it
one thing about filling pixels
you can set many pixels at once with SetPixels
this is reasonably fast
Im gonna prepare a Color32[] buffer full of transparent and .. yea.. do setPixels
hey you asked lol
yeah, sorry i didn't know if it was possible using the normal button
its cool
my b honestly
Basically lol i want to use Gizmos to create my minimap xD
aren't gizmos editor-only
Ya, but i want non-editor gimzos ;D
im sorry, but has anyone got any know how on this?
Building Library\Bee\artifacts\Android\d8kzr\libil2cpp.so failed with output:
ld.lld: error: undefined symbol: GADUGetAdErrorCode
its an error alright
so mm what would be the best to mimick gizmos outside editor 🤔
i have this code to automatically make a PolygonCollider2D in the shape of a circle sector, as such, but i would like some way to mask the sprite programmatically so that what you see in the collider is the only bit that's shown. how would i go about doing this? (it doesn't have to use the collider, but just some way to mask a sprite in a sector/arc with a customisable angle)
scratch pen ofc
(Ill leave now)
scratch pen ? 😮
nah its a scratch thing
the funny orange cat
imma let you be now, back to the backrooms
🤔 maybe i should just access opengl low level stuff so i can draw fast triangles on the screen ? that will be faster than bothering with texturing the minimap
that can still be done with this technique
just make sure the minimap camera only renders obstacles etc and doesn't render the ground
The issue is that i mask the rooms on which my player is not ( i have a tileset that draws black tiles ) .. so the minimap will be black ?
just don't draw that tilemap in the minimap camera
yes using culling masks
ok ! going to check this
Ideally i just want to render the walls
mm now i need a way for the camera to not render what the player hasnt visited yet .. hard ;D
someone in #💻┃code-beginner was just doing that :p
i'm guessing you want to do this per-room, though?
slap a trigger on the room that the player interacts with
basically .. i want to show the full layout of a dungeon for the room the player has visited.
haha now im thinking to have a tileset that is rendered only on the minimap.. i can do this 😄
It might be slightly harder if you want the rooms to always appear in the main camera, but only get put on the minimap if you've actually been in them
in the main camera i dont want to show the rooms in which the player is not
For gameplay ( i expect monsters to ambush the player) and perf reasons
maybe u can do some tricks on the culling mask
yeah i will do it
Good afternoon! is there a way to read an element from the queue without dequeuing(removing the element)?
I tried Dequeue(); before but it removes the element from the queue
Ohhh that what I was looking for, thanks!!
Can anyone help me out? Can't figure out to move an object move perpendicularly to my movement when i collide with it, on 2D
do you mean you want it to get pushed directly way from the player?
like if i move into an object from the left side it will be pushed vertically to the top or or down, etc
i edit the sentence, i missed a word when i was typing
well, let's see
so you need to find a vector that's perpendicular to the player's movement vector
Vector3.Cross will do the trick
The cross product can best be visualized as
A is gonna be your movement vector
B is the "forward" vector (the one going into the screen)
and then AxB will be the result
Vector3.Cross(rb.velocity, Vector3.forward);
alternatively, you could rotate the velocity vector
Quaternion.Euler(0, 0, 90) * rb.velocity;
I think that one make sit more obvious which way it will go
it's a 90-degree rotation
https://en.wikipedia.org/wiki/Rotation_matrix
maybe this is helpful but there already is a built in function
In linear algebra, a rotation matrix is a transformation matrix that is used to perform a rotation in Euclidean space. For example, using the convention below, the matrix
R
=
[
cos
θ...
and cross product is defined in 3d space, but you can treat z is 0
yes, there's no need to figure out transform matrices here :p
yeah, it's 3D only
fortunately, what we want is the cross with the (0,0,1) vector
Anyone know how to save an int value (to read from on next play) from another script?
on next play meaning "the next time the game runs"?
{
if (collision.gameObject.CompareTag("Enemy"))
{
Vector2 pushDirection;
if (Mathf.Abs(movementVector.x) > Mathf.Abs(movementVector.y))
{
// If moving mostly horizontally, push enemy up/down
Vector3 perpVector = Vector3.Cross(rb.velocity, Vector3.forward);
pushDirection = new Vector2(perpVector.x, perpVector.y).normalized;
Debug.LogError("Player Moving Horizontally:" + pushDirection);
}
else
{
// If moving mostly vertically, push enemy left/right
Vector3 perpVector = Vector3.Cross(rb.velocity, Vector3.forward);
pushDirection = new Vector2(perpVector.x, perpVector.y).normalized;
Debug.LogError("Player Moving Vertically:" + pushDirection);
}
collision.gameObject.GetComponent<Rigidbody2D>().velocity = pushDirection * pushForce;
}
}``` @heady iris changed my previous code and ended up with this, but the object still wont be pushed away
note that the conditional doesn't do anything here, since they both have the same code in them!
Do you want it to snap to the axes?
i.e. it only goes up, right, down, and left
how can i check if two colliders are intersecting, 1 box collider and 1 non convex mesh collider
It's relatively annoying to directly ask if two colliders are touching in 3D physics
just the 4 directions, you say the if doesnt do anything there then?
I'd just use OnCollisionEnter and OnCollisionExit to keep track
well, yeah, both blocks of code are identical!
idk if it works
i need to check when it spawns
i have 2 structures, and i need to check when another spawns, if it is intersecting one of them
private void OnCollisionStay2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Enemy"))
{
Vector3 perpVector = Vector3.Cross(rb.velocity, Vector3.forward);
Vector2 pushDirection = new Vector2(perpVector.x, perpVector.y).normalized;
Debug.Log("Direction:" + pushDirection);
collision.gameObject.GetComponent<Rigidbody2D>().velocity = pushDirection * pushForce;
}
}
```oh yeah, but still, the object **isn't** being pushed away perpendicularly
you'll get an OnCollisionEnter call
since you said one is a box, though
you can just use Physics.OverlapBox to ask for colliders in an area
even if i don't have the reference of the other two?
right, it just asks if anything (on the specified layers) is in there
oh ok
let me try
oh wait
i did try the overlap box
Physics.OverlapBoxNonAlloc(bounds.center, bounds.extents, new Collider[] {}, Quaternion.identity)
but didn't work
if you don't understand what NonAlloc means, do not use it
just use Physics.OverlapBox and loop over the array of colliders
it was suggested by Rider
Rider can suggest many, many things, but most of them are the wrong choice :p
Anyone know how to save an int value (to read when the game is next ran) from another script?
oh ok
use PlayerPrefs
How can i get the int value from the other script then?
Is there any way to change a component to an inherited version of itself? I had a bug script, and I want to retain the inspector properties, of which there are many, when changing it to an altered, inherited version. Previously, you could change the Script field in debug mode, but they seem to have blocked that off
I know they exsist but before i save the data i need to get the data from the other script (stopwatch script). How do i do that?
Yes.
oh, I see
I thought you were asking about having the other script get the saved value
well, you have a reference to the stopwatch script, right?
if so, you can access any public field of the stopwatch script
If you don't , add a field to the first script, public Stopwatch stopwatch; (or whatever you called the stopwatch script
and drag the stopwatch object into the resulting field
Alr thx.
thx, it was the NonAlloc
if you are curious
NonAlloc means that the method does not allocate its own memory. Instead, you give it an array you made yourself.
This means that it's not creating and destroying an array every time you use it, which can matter if you're worried about creating too much garbage
i.e. memory that was allocated and then thrown out
For example, I use it when I just need to check if something is in an area
and I give it a one-element array
I would only worry about that if you're doing this many many times per second
if it's just for when an entity spawns, and you spawn a sane number of them, don't even bother
depends on how fast the player is moving, but shouldn't spawn a lot of them
and just intersect max 4 things
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Enemy"))
{
Vector3 perpVector = Vector3.Cross(rb.velocity, Vector3.forward);
Vector2 pushDirection = new Vector2(perpVector.x, perpVector.y).normalized;
Debug.Log("Direction:" + pushDirection);
collision.gameObject.GetComponent<Rigidbody2D>().velocity = pushDirection * pushForce;
}
}
``` @heady iris its working now but i have 2 problems, the object will only be pushed away in a clockwise rotation and it is only pushed away if the Enemy Object isn't moving so my script of the Enemy Object Movement with ```csharp
private void FixedUpdate()
{
Vector3 direction = (player.position - transform.position).normalized;
rb.velocity = direction * velocity;
}``` on the Enemy object to make it follow me has to be disabled for to Object to be able to be pushed away
well, yeah, you're overwriting the velocity on every fixed update
perhaps the enemy should either get "stunned" and not move after getting hit
or it should gradually adjust the rb's velocity
what about the clockwise rotation
maybe the enemy is pushing into the player and turning as a result
you can check something on the Rigidbody component to freeze rotation
that might be useful
Sorry, should have explained better, what i mean is that the object is being pushed away in a clockwise direction around the Player Object, so if i collide with it from the left side he will be pushed down, etc
from above -» to the left side
from the right -» up
from under -» right
The idea is that if im for example, surrounded by enemies and i want to pass through them, they will be pushed away perpendicularly to my direction so that i can move through, and it would be weird if it only worked on a clockwise direction like this
so you want them to get pushed up or down depending on whether you're above or below their center?
and only get pushed in the cardinal directions?
if they are to my sides they will be pushed down or up, if they are up or down they will be pushed to the sides, depending on which direction i try to pass through
it would also have to work in diagonal directions i guess so i can move that way, but baby steps, was trying to get the other directions right first
@heady iris sent you a clip on dm
just make a thread in here, please
2D - Pushing objects away to allow passage
Any thoughts on how to implement floating unit icons as in Warno? So that even if units overlap, the icons will never overlap?
i think i ran into this before...
hmm
you could do it with Actual Physics
with 2D rigidbodies (with some serious limits on how fast they can move :p )
how so? sounds interesting
just standard collision behaviors would constantly jitter back and forth no?
sorry
you'd want them to be very heavily smoothed
is there a smoothing variable?
actually, one thing -- are those units part of a squad of some sort?
i.e. they're always together
that might make it easier
I mean, no, mechanically it's just single units
but you'd still want to have the icons stick to the individual units when you zoom in close enough..
You can feed units on the screen to a UI which will project world to screen position. And if their rectangles overlap to collect them into UI grid which will handle a lot for you.
very high drag, maybe
That was the other thought I had
yeah, abstract but probably true
UI grid specifically seems nice
Hey ppl, on Unity if i have two Monobehaviors object, referencing the same instance of another gameobject
ClassTest1
-----> ClassBase
ClassTest2
if ClassTest1 and Class2 execute the function
ClasseBase.SetValue()
var value = ClasseBase.GetValue()
can happen that Before ClassTest1 receive GetValue(), ClassTest2 have it changed too?
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
unity is single-threaded
Your question is very hard to understand but yes if you have two references to the same object, you can see the changes made to it in both places. You're looking at the same object after all.
they're asking if both scripts could call SetValue before one of them calls GetValue
Exacly
this cannot happen; the scripts on the objects will get updated in sequence
even if you spawn off some coroutines and have them mess with the value, they will also run in sequence
why gameObject.transform.rotation.y is returning 0.7018 when the rotation is 90 on the inspector?
Because .rotation is a Quaternion value, something that represents a rotation in a very abstract way
4 float values, ranged from -1 to 1
so, how do i get the real rotation?
sounds about right
.eulerAngles
oh ok
that is the real rotation. use euler angles if you want the euler representation
That spits out angles in degrees
it's generally not a good idea to read euler angles back from a Transform in code except for display purposes though.
This might seem dumb, but I'm having problems with rotating in 2d to the mouse. So, how to do that?
i just need multiples of 90
btw, is there a way to make float operations more precise?
myObject.transform.right = directionToMouse;
it's unlikely you need it.
Sort of. You can use double but Unity doesn't use it internally so it has limited use
I did that, but my character just gets its front to that direction, making it look paper thin
i completely forgot you could do this
you did it wrong
show your code
sounds like you did forward not right or something
or directionToMouse was calculated improperly
Correct, but it was something else
e.g. with a nonzero z value
Turns out I used transform rather than render.transform (render is an object for the sprites)
How do I make objects not collide with objects of a certain layer?
I already did the layer thing, but it didn't work
I did that
you must have done it incorrectly
show what you tried
also make sure you used 2D physics settings if you're using 2D physics
Is this 2D or 3D?
How do I get lightweight render pipeline? I can't search for some reason
Oh, ok, thank you
Has anyone ever used patch obb files for their Android projects (eg patch.1.com.myapp.demo)?
Hello, not sure if this is the right channel, but I'm having a bit of a problem with Mirror and Networking inside my project.
I'm using a Steam based P2P system, only two players. Each player has a parent object which gets filled with Instantiated prefabs.
Now i want a function, that "copies eachothers prefabs" into our parent, so our unique prefab list merges on both clients.
How should I get started with this?
Any idea why my Serializefield area isnt popping up?
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MapArea : MonoBehaviour
{
[SerializeField] List<Enemy> wildEnemys;
public Enemy GetRandomWildEnemy()
{
return wildEnemys[Random.Range(0, wildEnemys.Count)];
}
}
I have no errors so I dont understand why its not popping up
How is Enemy defined?
Is it serializable?
I want to grab an entire canvas mainly so I can set .enabled to true and false
putting the canvas in a GameObject doesnt seem to work so what variable do I put it in
Canvas
if that gives you an error message - read the message as it has important information for you, and check what auto-fix suggestions your IDE has for you.
it sort of works, it unpauses but it cant pause @leaden ice
well yeah
look at your code
shouldn't that if be an else if?
am I missing something obvious
better code for this:
void Update() {
if (Input.GetKeyDown(KeyCode.P)) {
paused = !paused;
Time.timeScale = paused ? 0 : 1;
uiPause.enabled = paused;
}
}```
no need for the duplicated code.
it sets time scale to 0 if paused is true, 1 otherwise
alright thanks for all of the help
I just put it in and for some reason this doesnt bring up the UI, the game still pauses but the UI doesnt get enabled
I have implemented a FSM for walking, jumping, attacking etc where all are different states. Is this a bad approach for game design as most of the time things are overlapping? The user should not notice these, after all
shwo the code
and show the inspector
I got it to work now
what I did was enable the canvas in my inspector but disable on void start
Greetings,
I have a editor window script that references a TextAsset. I want to open the TextAsset at a specific line-number in vscode. I'm using the method AssetDatabase.OpenAsset(). It does work properly for .txt files.
However, I have created a custom file-type ".aljs". I created a ScriptImporter that imports those files as TextAssets. I have a custom vscode extension for this file-type for syntax highlighting. AssetDatabase.OpenAsset(). opens the correct file, but it does not jump to the correct line. The documentation (https://docs.unity3d.com/ScriptReference/AssetDatabase.OpenAsset.html) "If it is a text file, lineNumber and columnNumber instructs the text editor to go to that line and column."
Is there a way to make it work for my custom file-type?
I have a workaround in place, but it's kinda bad. It starts a process before which opens a console window for short and it's kinda slow.
string filePath = AssetDatabase.GetAssetPath(textAsset);
string fullPath = Application.dataPath + filePath.Substring("Assets".Length);
System.Diagnostics.Process.Start("code", "-g \"" + fullPath.Replace("\\", "/") + "\":" + 15);
AssetDatabase.OpenAsset(textAsset);
Does someone know how to make it work without having to start an additional process?
Kind regards.
I have a "sheath" animation that my character is engaging in here, but this involves reparenting the sword from the character's hand to their back. the animation runs in a coroutine while the reparenting is done imperatively, i'd just like to know what the most straight-forward/idiomatic way to do the reparenting at the right moment in the animation would entail. should i just try and figure out exactly how many (milli)seconds into the animation is the right time for the reparenting to occur and then do the reparenting in a coroutine that waits that long before starting?
animation events seem like the best option in my opinion, their purpose is to do exactly that: execute code at a specific time during an animation
https://docs.unity3d.com/Manual/script-AnimationWindowEvent.html
wow that rocks, thanks so much glad i asked
So i'm trying to use a tilemap for the in game map, for some reason some of the white edges dissappear in game
notice in the top right how the rectangle doesnt have the bottom edge like in the editor
are you using a pixel perfect camera?
you should be
btw is using a tilemap for a map a good idea
I thought of doing it cause it would make it easier to make levels
why cant the pixel perfect camera rotate down?
it didnt do anything?
Is it cause im in 3d?
wdym by "in 3d"?
you should be using an orthographic projection on your camera if it's a 2D game, if that's what you mean
my game is 3d also it says that render texture doesnt support the pixel perfect camera
I'm getting weird stuttering with Cinemachine. I've got some camera math that updates in FixedUpdate and then interpolates in LateUpdate, which is important for the kind of high-speed type of game that I'm working on.
This works perfectly in raw code, but every time I try to get Cinemachine to run it, even when I'm updating all the data manually. I've tried switching the update method and calling ManualUpdate from within LateUpdate.
Something about Cinemachine's internals or the MutateState function must be failing to apply the camera transform properly. Does anyone know what could be causing it?
