#archived-code-general
1 messages Β· Page 155 of 1
TransformPoint takes a local vector
hmm
sorry Camera.main.transform.TransformPoint
offset is a float
in my example
If you want a viewport point you can also do:
float distanceFromCamera = 5;
Vector3 viewportPos = new Vector3(0.5f, 0.5f, distance); // right in the middle of the viewport
Vector3 worldPos = Camera.main.ViewportToWorldPoint(viewportPos);
thank you, I might get it from here
Im reworking my entire inventory system because it was really really poorly done backend so I might have more questions
- worked
swell
ill model an arm later
Are you making a Backrooms?
i am making a backrooms
been going for a couple months now
have 2 levels done well with a third one on the way
although making a level doesnt take a month that also included setup and stuff
Oh, neat, the beginning of a project building all the systems to automate development later, does take a lot of upfront time, good to hear your making progress
thanks!
it was also just building the mechanics and such
many of which were very poorly done but functional
also like two weeks to realize how stupid I was on optimization
first commit was start of april
I made the very good and wise descision to not properly name things in blender and now have 30 materials called "Material.001"
Functional is good, if it helps, you could look into inheritance, interfaces and "micro services" or "broadcasters/messages", they can essentially replace singletons and heavy dependencies, and both services and broadcasters dont require MonoBehaviour so they dont need to exist in any scene to work, interfaces could let you make shared functionality, like allowing anything with IDamagable to take damage or IInteractable to be picked up, etc - and inheritance would let you create base scripts, so you could have a Weapon : Mono and then a Axe : Weapon etc, might help organize your code, I found them a big help at least in my projects
im using inheiritance
I use abstract a lot
I have that with Damagers, items, interactables
Ah, abstract is good too, I use virtual more often personally, though either approach should help in less messy code, what do you think is "poor" about your approach?
ehem
my code is pretty bad
its very messy
this is probably the worst offender tho, the script that stores all the player stats
(and manages)
I think you should consider using headers and spaces
and serialize fields
im getting better with Serialize
im using it more
Hey guys posted previously on #π»βcode-beginner too so I'm sorry if this is not ok. I'm trying to use Quaternion.RotateTowards, but instead my object of pointing at the target, it I think tries to point to where the target is looking towards, resulting in my object literally pointing away from it.
thisT.rotation = Quaternion.RotateTowards(thisT.rotation, targetUnit.thisT.rotation, Time.deltaTime * trackingspeed);
this script was written a while ago
I mean, it does seem like you are telling it to point at the rotation
just tell it to point at targetUnit.transform.position
Quaternion.RotateTowards doesn't allow using position unfortunately
It only allows quaternions
oh shoot wrong discord lol
hmmm
theres a way to get the rotation towards something
you could also try Transform.LookAt()
Some things that could help, if you want to "collapse" related data, you could put them in a serialized class
[System.Serializable]
public class WeaponData
{
//...
}
[System.Serializable]
public class WeaponDependencies
{
public SomeComponent example;
//...
}
public class Offender : Mono
{
[Header("Weapon Stuff")]
[SerializeField] WeaponData data;
[Header("References")]
[SerializeField] WeaponDependencies dependencies;
}
Or you could put it in a ScriptableObject instead, then you can create those SO files and even swap out data or have other systems share the same data if you wanted, I personally like combining the two approaches to also allow me to save that data to JSON if I wanted, but no reason the data couldnt just exist in the SO if you prefer
[CreateAssetMenu()]
public class WeaponSO : ScriptableObject
{
public WeaponData savableData;
}
but that doesn't do it smoothly
Yeah I need it to be smooth since it's a homing bullet. Thanks though!
nono I gotchu
It does rotate oh so very nicely away from it! :)
Vector3 targ = Player.transform.position;
Vector3 objectPos = transform.position;
targ.x = targ.x - objectPos.x;
targ.y = targ.y - objectPos.y;
targ.z = targ.z - objectPos.z;
transform.forward = Vector3.Slerp(transform.forward, targ, 0.1f);
here you are
(sorry about weird spacing, copying from visual studio sometimes does that)
Thanks i'm going to try that.
did it work out?
is it possible to have a mesh be always rendered on top of another one? I know in fps games they do a thing with a static image but that wont work here
I have tilemaps with many different tiles with different types of logic. My issue is if I use a composite collider, I need to figure out the ID of the tile I hit. If I could find out what cell on the tilemap I made contact with, I could easily take it from there. Any suggestions?
do particles stay if the spawning object is destroyed?
how do you scale ui equally across all resolutions?
Yes . . .
Check the docs pinned in #π²βui-ux for info about scaling and anchoring your UI
will using scale with screen size give me problems though
can someone heelp with my error InvalidOperationException: You are trying to read Input using the UnityEngine.Input class, but you have switched active Input handling to Input System package in Player Settings.
UnityEngine.Input.GetKeyDown (UnityEngine.KeyCode key) (at <82ff21ca19ff4a6c94c6df953addbbcc>:0)
Gun.Update () (at Assets/Scripts/Gun.cs:13)
is it not letting you run the game? I have gotten that error before
Did you read what it is telling you?
I think if you go to your project settings(Edit/ProjectSetting/), check Input system package and input manage
you might find something there
This error is quite specific, look at the file and line its telling you to look at
I dont even think it is a problem that stops anything as i have gotten it befor
Hey can anyone explain to me please how I can get this script running?
wheres input manage
It adds a function to the unity editor which I havent done yet. it lets you reverse animations
Well it is an error.
input manager
o
go to project settings
ill take a pick of my error
Please actually read the error you are receiving
lemme see ur script
Im new to0 this
!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.
gun.cs
one sec
ok
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gun : MonoBehaviour
{
public Transform bulletSpawnPoint;
public GameObject bulletPrefab;
public float bulletSpeed = 10;
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
var bullet = Instantiate(bulletPrefab, bulletSpawnPoint.position, bulletSpawnPoint.rotation);
bullet.GetComponent<Rigidbody>().velocity = bulletSpawnPoint.forward * bulletSpeed;
}
}
}
Being new doesn't preclude you from paying attention to what the error is telling you
i coded it not sure if i messed up
The classic goose chase
Trying to find the error when the error tells you exactly what line its on.
And why it's there
i know how to fix ity
Also !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.
go to player settings, in the search bar type active input handling
set it to both
or project settings
Just use the new input system if you're gonna use the new input system...
how
guys im making a script for my enemy to die, but i want the shatters Destroy after 3 seconds, but my original gameobject not shattered is already destroyed and replaced with the shattered one without any script, and i have an IEnumerator.. How do i make my shatters destroy after my gameobject with the script has been destroyed?? Here's the script: https://hatebin.com/plnsckrqfq
thank you loganπ
did it work?
You really dont need to do that, you've been sent on a goose chase. You've enabled the new input system and arent using it, that is quite literally the entire error.
yea
hello guys, I can't move my character, it's moving by itself right to left until it stops
is it because of this code?
@shadow grove
yeah i guess
but he is probably following tutotrials that use a mixture of both the old input system and the new one
maybe because if you press it you are not checking to see if the key has been lifted, so nothing is stopping the force from continiung
π€·ββοΈ no point adding the new input system if you are gonna checkmark to use both, then only read input from the legacy system
so check to see if one key is lifted then clear the force
- don't addforce in update except for one-off forces using ForceMode.Impulse, do physics in FixedUpdate
- don't multiply your forces by deltaTime
- reduce the amount of force you are applying
- provide more actual information about the issue you are experience, see #854851968446365696 for what to include when asking for help
Guys, is there anyway to start a coroutine after the gameobject is destroyed?
not on that gameobject. you can start a coroutine on some other game object though, just fire an event in OnDestroy or whatever to notify subscribers that the object has been destroyed
do i need another script for tht?
data writing question - I have a script that encodes barycentric coordinate data into mesh vertex colors.
The data only needs to be encoded one single time. I am not versed in editor scripting however, is there some way I can write that data into the meshes, outside of the scene outside of at 'Start'?
because I dont want to be setting meshes to writable at runtime and calculating this at Start if it can all be pre-packaged
currently the method I use to write the data only works in editor and fails in build because its happening OnValidate, but the mesh isnt permanently gaining that data, it's local to the editor scene
well you do need to write code to do it. whether you put that code into an existing scripts or some other scripts is up to you
what does this mean
is it dangerous or no
seems like you're destroying a prefab rather than the instance of an object
bruh
Why is every script that contains an Awake function disables them selfs when the object instantiates? I didn't have this bug this morning but now all of the sudden I do. Anyway to fix this? Could this be the cause of netcode networking?
(other script)
i don't know what you think this is supposed to prove considering it does not show that you are or are not passing a prefab
This happens if your code throws an exception in Awake
if these are network objects you probably need to make sure they are spawned on the network and not just instantiated
that is a variable that contains the shattered version
is the "shattered version" a prefab?
yeah
so you're passing a prefab to Destroy instead of the instantiated instance
which is exactly what i told you already
as I said everything was ok before, I used the same things. But after some time I did some scripting on other scripts and it caused that issue to disable every single script that contains Awake. Plus most of those script doesn't even have a NetworkBehaviour nor networkObject
but i destroy the original not shattered version and instantiate the shattered version from the prefab folder man
not what your code says
either way you shouldn't be destroying "the original". You should only be destroying scene instances
not the original prefab in destroying, the instanced one
Fixing all bugs would fix it you say? Most of the bugs that I have makes no sense but I'll see what I can do.
I didn't say fixing all bugs would fix it
I said a very specific thing
if your Awake function throws an exception it will disable the script
the strange thing is that I don't even have any bugs I just realised. It's marking random lines and saying that that's the bug even thought it isn't cause it worked 2 hours ago and I didn't change anything in there
it's doing that on 10 different scripts
but you literally just said that the destroyedVersion variable is a reference to a prefab
plus I'm not even sure if it's cause of Awake functions.
I don't even have any bugs I just realised
If your code is not working as you expect, that is the defnition of a bug. You are confusing errors with bugs.
It's marking random lines and saying that that's the bug even thought it isn't
I believe the compiler over you, sorry.
If you want further help, share your code and the error messages you're seeing
forget it
I thought it's cause of that cause only the scripts that contains an Awake function got disabled. But the null exception bug marks that it's somewhere else
Any time an exception is thrown from Awake, it will disable the script
that's it
Hey again, i'm working on making my voxel engine allow beveled edges.
I believe there will be 2^14 possible block combinations, so a dictionary of size 16384, that sound reasonable? LOL
you need to pass the instantied "shattered version" to Destroy instead of the prefab. but if you are just going to give up because you don't like what i'm telling you, then good luck π€·ββοΈ won't last long in the dev industry if you give up at the slightest inconvenience
quick example of one script that is throwing this error. And the line
its not because i dont like what you are saying, its because i am not understanding and i dont have much time to explain
not going to show more code cause it wouldn't help either way most likely
Key binds is null
the destroyedVersion variable references a prefab. you instantiate that prefab somewhere. but instead of storing the instantiated object and passing that to Destroy, you pass destroyedVersion which as we have established is a prefab. hence the error about destroying assets because prefabs are assets
An NRE occurs when you attempt to access a member (field, function, property etc) of a variable while the variable is null.
looks like keyBinds is null. The error makes perfect sense.
this should work right?
No certainty
k that is the reason some how. Can you explain how is this not getting the keybinds script? :P
because there's no _Keybinds component attached to this GameObject (the one this script is on)
i mean, i guess. but you should just store the reference when you instantiate it. you can even just call Destroy on literally the line right after instantiation because you can pass the delay to Destroy instead of using a coroutine
and for future reference, if you don't understand something then fucking ask. i have no way of knowing what you do or do not understand so you have to make it clear so it can be explained
It did not exist when you tried to find it - would be a possibility.
there is
this screenshot shows nothing
it shows that script is on some object
Stop it with the miniscule images please
wdym delay of destroy
this code also doesn't actually show where this line is
or prove that it's even running
!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.
Not enough info as is
We're just certain that it's null when it's executed - assuming that's the correct script/location
no way they had that and i didnt know
bruh cmon π
pay attention to the docs and what intellisense shows, you should have seen the tooltip with the parameters in your IDE
i dont read that much docs
You only have ONE GpulseTurret in the scene, guaranteed?
fix that
you CAN'T make games or write any code without reading docs
constantly
ok wait give me a sec I'll figure out something. The issue is that it's not getting the components at all so I'll just add em manually. Still don't understand why is it like that
idk man its hard to interpret
It will be for standard/typical reasons. There's no mystery:
- The component isn't on the same object
- The code that sets it isn't running
Tbf, the simpler your game is the less reading you'll need but still.
im kind of lazy
the component is on the same object. The reason why is it not getting it is cause the component that should be getting it is getting disabled for who knows why
man why tf does it keep counting as a prefab
so if it's disabled it's not running the awake at all and not getting the component
I might be able to fix the issue by simply assigning the components instead
it's getting disabled because of an exception being thrown in Awake
You need to look at your console
find the exception
and fix it
there's no magic.
show the code you have to destroy the object now
you're literally just passing the prefab in to Destroy
not sure what you expect
it does exactly what you tell it to do
assign the returned object from Instantiate to a local variable and pass that in, not the prefab
then how am i gonna spawn them by script in my terrain?
huh?
these enemies will spawn randomly in my terrain
so?
i'm guessing you haven't bothered looking at the docs or tooltip for the Instantiate method
it returns the instantiated object
one minute, i will have to translate this
ok, im gonna try
nop
show what you tried
i didnt change the script, i just spawned a shattered one in the world and used it in the variable
wait
one sec
How do you guys handle child and parent colliders that are triggers? I can't seem to separate them. In the screenshot, both of these have triggers on them and both trigger the OnTriggerStay function of the parent
You would have to put a kinematic rigidbody on the child if you want to separate the messages
Side by Side or multiple kinematic rigidbody
all colliders under a Rigidbody are part of that body. So the Rigidbodies are the separation points
Ohhhh, ok I'll try putting a RB on the child GO. The parent is currently the only one with one on it
i didnt change the script, i just spawned a shattered one in the world and used it in the variable
and it doesnt work
That worked! Thanks a ton guys π
well obviously. that's not what i told you to do
this is literally as simple as doing var obj = Instantiate(destroyedVersion); Destroy(obj, whatevertime);
Why not just do what has been recommended to you?
Because what you just said makes no sense
idk wtf i have to do, i dont speak english man
read the messages
im just translating things, and most of them doesnt make sense for me
that's what happens
the console doesn't says about any error, my character is a game object with both box collider 2d and rigidbody 2d, only with the script for the movement
i gave you the answer #archived-code-general message
Doesn't look like he's got a box collider
like this?
please take some time to understand what you wrote yourself
simulate that code in your head, taking into account what you learned about method returns
yes
it does
(sorry for the bad image quality)
can i put the destroyedVersion variable object from the prefab or no?
yes, the destroyedVersion variable should be a reference to the prefab
ok
The video illustrates that it has somehow got colliders for arms and feet.
IT WORKED FINALLY
thank you
and im sorry too
the character is made of body parts (body, two eyes, two feet and two hands), all of them inside the GameObject
should I put a box collider only on the feet?
If they're all solid, they'll force one another to be displaced if intersecting. You can use the physics layer matrix to have certain colliders ignore each other.
https://docs.unity3d.com/Manual/LayerBasedCollision.html
I'll read it, thank you
Hello, i am checking how the directions work on the built in wheel colliders and would like to replicate the same results with a raycast
anyone know the correct math functions to get this result?
it seems to stay flat to the surface but uses the steeringangle sort of to like follow the wheel
I think i found it these 2 lines seem to reproduce the results exactly like the wheel colliders
forward = (-Vector3.Cross(rayHit.normal, wheel.transform.right)).normalized;
right = Vector3.Cross(rayHit.normal, wheel.transform.forward).normalized;
just need to make the transform.right and forward be adjusted with the steering angle
I have a script that requires a couple of gameobjects with their own components, and I find myself making a lot of if(component!=null) statements for these references. Im setting these systems up in prefabs but dread the possibility of somehow running into a null pointer exception. Is there some way to make it impossible for instances of these prefabs to have their references emptied or something?
Ive considered making the references properties where each time I reference them I do a "GetComponentInChildren" but im not sure if this is even more wasteful than doing a null check in almost every function.
You can just check if its null once and throw an error if it's supposed to be there. If the script is on the same object, then u can use [RequireComponent()], I forget the exact syntax
make the variables private so other objects cannot access them. use the RequireComponent attribute to ensure your components are on objects that have the required components. serialize the references to the other components so you don't need to use GetComponent or whatever in Awake/Start. use TryGetComponent in methods where you are calling GetComponent and doing null checks since it combines both into one line
What im doing right now is making a script for each child object which holds a "RequireComponent" and Property accessor to the component, then I slot references to those in the parent script.
I guess my explanation boils down to 2 questions.
- Can I trust prefabs to not randomly lose data
- Is it really okay to have a script that will trigger errors if one of its references is null.
The error would be so you know that the reference has not been assigned. It shouldnt randomly lose its data, especially if you're just referencing stuff in the same prefab
does anyone know why my projectile randomly just ignores all collisions/triggers? if I get a certain distance away from the firing object, it collides but too close and it just goes through it.
how are you moving it?
adding relative impulse to a rigidbody attached to the projectile
make sure that the collision detection on the rigidbody is set to continuous. it's possible that it's moving too quickly for it to properly detect collisions
you have to freeze the rotation of player's Movement
hold on im gonna open unity to show you
here
Does anyone know where I can get code for a mobile game controller mechanics (just need for left and right movement - x axis)
anyone know a good video? or have a good procedule map generation?
do you mean the "z"?
I did this and my character started trembling
like this
Is the built-in untiy character controller any good for controlling movement of vehicles such as a plane or helicopter? If not, what would you recommend? Should I write my own character controller from scratch?
Additionally, I was looking at the free Kinematic Character Controller on the Unity Asset Store which was built from scratch (specifically for character movement). The script is almost 2k lines long. Obviously it adds a lot of features that the built-in CharacterController doesn't offer out of the box. However, I noticed the asset doesn't even leverage the built-in controller and build on top of it. How come?
Depends how realistic you need it to be. If not realistic at all, then it should be good enough. If somewhat resembling real plane or helicopter movement, then you'd need to implement your own or look for an asset.
Simply because the built-in character controller is not very useful for anything slightly more complex than a very basic arcade game.
how come? the asset is conceptually different to every other approach before it
those 2k lines achieve very barebones functionality, compared to other assets, that have ladders, wall climbing etc
however kcc has almost zero edge cases where it fails at whats advertised
what is hapenning here i just opened unity
i assume its not zero, but i havent encountered a single case where it would get stuck or broke on any geometry
and the way its designed gives you full access to all transient data, and has several extension points during internal phases where you can extend to do whatever you want
as for planes nothing built in or kcc or cc will work
either DIY with forces, vector fields for surfaces or some asset that does the same
You see to have imported the "Standard Assets" package which is very outdated
yes i do but 2 minutes ago it was working
this is hapenning
you don't have a class called Waypoint
but how does it suddenly makes this error
how should I know
you don't have a class called Waypoint
so it doesn't work
prove me wrong
maybe you deleted the Waypoint class?
Or maybe Waypoint is in another Assembly?
so what do i do? i have to create a script or smt?
there is literally no way for me to answer that
are you following a tutorial or something?
Do what the tutorial says
nah man
u either have to re-create it orr.. u have to delete all teh scripts that try to reference it
last time i closed unity was when i finished a script
you couldn't have gotten to this point without knowing what to do unless you nabbed this code from a tutorial or something
and i tested it
or from a library
it was perfectly fine
in which case - install the library properly
well, i tried to import an asset
it said that it would mess with my scripts and blabla
but i clicked "No, Thanks"
what do you mean by "it sauid would mess with my scripts
let me screenshot it
i have a feeling
man
i think
waypoint circuit and waypoint progress tracker is from the asset
idk
how is this been created in 2016
i created this project 1 year ago
where is Waypoint defined?
The RealisticDrone creator made it in 2016 is my guess
the waypoint error stuff is coming from Unity's Standard Assets
which i guess was used by the Realistic Drone asset
i downloaded the old assets
i have both waypoint scripts he has
altho straight from unity that script inherits from MonoBehaviour
not Waypoint
broken asset, there is no Waypoint
why are you even using the Standard Assets anyway? they've been deprecated and replaced with the Starter Assets
oh i see, it was because of some other asset
#archived-code-general message
the Realistic Drone asset he imported uses it's Waypoint system.. and changed it to inherit a script its missing lol
ya.. and then the didnt even include the Waypoint script
so. solutions are.. delete the asset, or figure out what Waypoint was meant to do and rewrite it, or better yet just delete that out of the asset and re-do a waypoint system of ur own when it comes time
if I make a bunch of trees with terrain painting, is there a way I can make them all interactable? I want to be able to chop them down
or would I have to manually place all the trees lmao
may have some useful information in this thread
the one about terrainData a few posts down specifically
sounds complicated
Ive normalized each of my vectors but still am having an issue where the player moves faster when going diagnol. Anyone know what else I can do?
yeah for sure gonna need to see !code for that
π 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.
have we ever found out why everyone does this? :
private int placeHolder;
I know it's preference but where did it start?
Unity used some conventions from C++, some people use some mismatched conventions that are considered legacy, and others use the Microsoft .NET/C# conventions (+Unity uses them for new packages)
Oh right, wasn't unity built in C++ aswell??
Yes
Alright thanks for answering my 3AM questions
It's pretty normal to do private fields in camelCase, or _camelCase, for C# in general
Pythagorean theorem
normalizing a vector solves the issue you are alluding to. when you normalize a vector it's length becomes one, so a vector2 (1,1) becomes )0.7071, 0.7071) when normalized
Hi! I have a problem with limiting drag distance in my darg and snap script. The script is not limiting the drag distance but placeing the object to the player with the distance of maxDistance also it's made to work for multiplayer. here is the script:https://hastebin.com/share/tefulilutu.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Can anyone help i have been stuck on this problem for over 2 weeks
Hello Friends, this is Otz, I am having some programming difficulties, it's terminal, and I would like some assistance. I'm attempting to rotate some platforms, but I'm having a few different issues. This problem has been very complicated and unnecessarily difficult for me to solve. Here are all the details, code examples, and demonstrations, as well as everything I've tried to come to a solutiojn -> https://stackoverflow.com/questions/76735104/unity-how-can-i-rotate-multiple-objects-in-a-constant-matter-without-using-par
Hello! I appreciate the quick response, but I actually did try that, as mentioned in the post. The issue is that the panels rotate around a parent object, which is also rotating, meaning the the objects move around in a circular pattern. This causes an issue where the location of the panels during their rotation is not consistent, demonstrated in this video, linked on the stack overflow post -> https://youtu.be/aa82rNaTyzs
Creating a parent object for the panels to rotate around/with is not a viable solution. It's not a solution because the parent is rotating with the children. This means the panels location is not constant and the panels visibly move around when rotating in large intervals, which is very jarring.
I thought I came to a solution when I crea...
Could you elaborate on what you mean exactly?
How could I implement it so it's done correctly?
By this comment did you mean I was brute-forcing it by rotating panels individually or by rotating the panels on individual parents?
I moved on to a different solution because people suggested I should. People suggested a fix, I implemented it, and the fix didn't work. I've really only tried two approaches: rotating on a parent and rotating the individual panels. If I knew why it didn't work I wouldn't have asked for help π
Hey, can you tell my why is value between 0-1 on animationcurve , can I changde it to be like 3000 on X axis ans 700 on y?
The value on an animation curve is 0 - 1 because it means from 0% to 100%, so I don't think it can go above that amount
Though I've only used them a handfull of times so not 100% on that
in window? I could not, can you suggest a way?
here?
I remember I could change this here but I am on 2022 lts, is there anything changed?
:d
I used this but
it still does not go above 0-1
I can drag it but, how much I have to zoom out
to get like 2000
from 1
I remember somehow it can be changed
How do tou do? Using new KeyFrame()?
Hm how
No, do not open it
I click right key
an this happens
when clicking
it adds
Not working
it still shows Add Key
I asked gpt to create this
but
when I open I cannot modify because it is zoomed in
Ahhstrange
π
Okay, thank you, maybe it is a bug, or feature of new 2022 lts
idk
What was your solution that you had in mind for this?
But... the point of the post is because I wasn't able to figure out what went wrong?
What do you believe I am doing wrong?
What information about the bug do you believe you're missing that would be helpful to find a solution?
Hey guys, i've checked out 5 tutorials for the VFX Graph, but no matter what i try, when i create a VFX Graph etc i just see a teacup, no particles or effects. What am i doing wrong?
Ask in #β¨βvfx-and-particles
I've spent a lot of time debugging before posting. What information, when provided, would be helpful for you, because I feel like I've done an adequate job describing and demonstrating the problem I've had with both approaches
I need to know what you need, so I can help you help me
Is there any notable information you're trying to find? It sounds like you're referencing a specific setting or other. I can simply prvide the information you're looking for, be it the position, rotation, or otherwise
The only things I would've done are:
1 - Import the models and put into the scene as game objects
2 - Position a 6 of the models
3 - Set the rotation of all 6 of the models
4 - Create parents and set them as children
All the information is contained in the Transform component, which and the hierarchy is visiible in the images. The transform component only has scale, rotation, and position, so It's not like there's any complicated steps I could've done or settings I could've messed with. All the information is there, any any information that is not I can provide, so I'm not exactly sure what you're looking for and it doesn't sound like you know what you're looking for either
Step 5 would be to run the code that's shown on the post
Could you let me know what information you're trying to find?
Again, there are very little settings in the transform and no other scripts attached to the platforms
go ahead
Could you let me know what you mean by the pivot is correct?
The only way to change the pivot in a 3D scene is with a parent, no?
Referring to the model or the game object?
That's why I was confused
you're suggesting the pivot of the model is off?
Good night
How do I get rid of DontDestroyOnLoad and how did it get there
huh remove the line
what line
DontDestroyOnLoad
then there is no DontDestroyOnLoad object
it only shows up when i press play
but is it empty?
no
so whatever is in it has DontDestroyOnLoad on it
That's a scene, not an object. It's there to store debug stuff sometimes, I've seen
how do i get rid of it
You don't
it's part of unity
how did it get there
for DDOL objects
It's required for the said debug stuff to work
how do i stop it from loading objects into the scene then
You don't, it's required for the said debug stuff to work
How about you expand it to see what's in it?
"[DebugUpdater]"
There we go
whats that about
The debug stuff I've been talking about, like 4 times
its the entry point for debug
ill look for something else
You cannot get rid of it. It's required by some Unity package or object
like what
it's normal in SRP
Yeah that's the render pipeline thing
i mean what kind of object
inside Core RP Library i think
Why care about it? It's required to work, so you don't touch it
you shouldn't worry or touch it
ok then
You were pretty intentionally unhelpful and rude most of the time but I think I may have identified the problem
it won't be in your build so who cares
Anyways, peace
One more thing, how do I detect if two objects are touching from a script thats not attached to either of the two objects
Probably more trouble than worth, but get the reference of both the objects then do overlapsphere or distance check with the widths of the objects
ok
Another option would be to have an event that gets invoked when the objects collide. The third object that needs to know can subscribe to it
No one can help if they don't know what the problem is
this
When I stop the playmode I get this error:
Cannot set the parent of the GameObject 'Player(Clone)' while activating or deactivating the parent GameObject 'Parenting Obj'.
UnityEngine.Transform:SetParent (UnityEngine.Transform)
- and this is the code snippet that is causing this to happen
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.TryGetComponent<Controller>(out Controller x))
{ collision.transform.SetParent(null); }
}
of course the error doesnt happen when the game object isnt in the trigger... but it still annoys me if i stop playmode while the player object is on the trigger... can someone help how I remove the error? I tried to use Try/catch and it didnt work
You could try setting the parent in a Couroutine with a slight delay. It would desynchronize it though.
Thank you... I will try it π
Hey, will OnEnable() be called if I turn inactive and active the object in a frame?
Yeah I figured aha ty
Can somebody point me to any good article about the practical serialization of parameters for saving, instead of the ones that merely state that serialization is possible and you should use it?
I'm making a save system for my game to do persistent changes in the levels, and so far I managed to code a system to store most of the basic variables by converting them to strings in kind of this hierarchy:
dictionary of data from all the levels; by level's name
dictionary of all objects on a level; by object's unique GUID
dictionary of struct that contains variable's name, value, and type; by variable's name
converting seems simple - for most variables just .ToString() is enough.
However I'm not sure how to proceed for stuff like dictionaries, structs and most importantly - referential links (for example my camera prefab can be set to look at a specific gameObject instead of at the player - how do I store and restore this change?)
From what I was able to gather serialization should do exactly this - convert a variable to a string entry and be able to convert it back from it to a variable.
However, most articles are either talk about this in a very abstract way or basically say only "just put [SerializeField] before your variable declaration, lol"
serialization is just a basic concept that means "converting a complex graph of data in memory into a serial form so it can be written to a file or sent over the network"
In practical reality there are many tools for serializing things into many different formats, and each of these tools has is own set of very specific rules about how it works
But from your description here I think before you even get to that point you really need to step back and have a think about what information you actually need to serialize
converting seems simple - for most variables just .ToString() is enough.
Also this seems like you are trying to build your own serialization tool from scratch, which I wouldn't really recommend
- Is there any real reason why should i avoid binary formatting? Other than "imagine if hackers publish your game with modified binary" or "microsoft says so"? Like, real reasons
Well, like I said, all articles are saying just that serialization is a thing that exists and here's a couple of interfaces it uses, but not how to actually operate it for your own goals.
There is JSON serialization, XML serialization, binary serialization, and many other random serialization formats. There are many libraries for C# serialization on github that have in-depth documentation on how to use them. All you need to do, most of the time, is somehow tag certain objects and variables as being serializable (usually with attributes) to get them serialized. To "actually operate it for your own goals" depends on what your goals are. All it does is turn your variables into bytes or text that can be written to a file, and then read back later. Unfortunately you cannot just serialize your whole Unity scene and boot it back up. What you have to do is a bit trickier.
If you are serializing your camera that is set to look at another object instead of the player, that object would likely need some ID that gets serialized along with any other relevant information such as its position, rotation, health, whatever. Then, you need to write code more like "Look at thing with this id", in theory at least. Loading the game would mean deserializing the save file, and recreating the state of the scene via your IDs and whatever other information you might need to reconstruct it. Perhaps, first, you would serialize the type of prefab the object is, then the custom instance id of that object, and then the other information (in that order). Reading it back, you would need to use the prefab id to map to some prefab in your game, then you would instantiate it. You would assign it the instance id next, then you would assign all the other relevant data. Your camera would undergo a similar process. The camera code would then need to try and use the instance ID to get a reference to the object's transform at "runtime", post-serialization.
Experimenting with what you can and cannot easily do with serialization will define how you structure your game state, and it is not something that could be fully covered by some tutorialβassuming your game is anywhere near complex.
Hello, I am a little confused about prefabs, basically I imported models, gave them components/values and then turned each into a prefab.
Then once a prefab is instanced in the scene, it's made up of two gameobjects, the root of the instanced prefab (that only has a Transform component) and then there's the child object that is the actual model and components.
Isn't it kind of a waste to have two gameobjects?
I am making a level editor, so I can spawn and place props ingame and those props are selected by raycasting and the collider is on the child object (of the instanced prefab).
So I am left wondering if I should update the transform of the child object, or the root/parent (that is, the instance of the prefab).
I think it is a good idea to always work on the parent object whenever possible.
When I can, I like to put my collider and scripts onto the parent object, and have the graphics be the child. Sometimes this is doesn't work well, like if you have a skinned mesh and need to have colliders that move with the bones, but most of the time it does work. But if every single prefab has a parent for no reason, then I would say it's unnecessary. You would have to actually be using the parent for it to be relevant.
Because serialization is just a concept not some specific library or whatever
If you are serializing your camera that is set to look at another object instead of the player, that object would likely need some ID that gets serialized along with any other relevant information such as its position, rotation, health, whatever. Then, you need to write code more like "Look at thing with this id", in theory at least.
Hm, so basically "references can't be serialized, you need to do hacky ways around that to retain them"? This sort of sucks.
Yes, it does suck.
This is why data driven approaches to game development can be nice. This kind of ID mapping is usually built-in (Entity Component System for example), or you don't need many references in the first place, but you will always have to deal with Unity gameobjects being instantiated / destroyed on save / load.
then again, luckily I don't think I have many that are worth preserving yet, I think it would be only in the camera object and the NPC's AI system.
Thanks, I'lll use the parent, though just wondering, is there a way for the prefab to be a single game object?
If I'm making a sports simulation game, what's the best way to preserve data? a relational database JSON? Something else?
What do you mean? You mean is it possible for models to also be a prefab?
I am actually not sure, I will have to check if there is a setting.
I don't think that my prefabs have any additional parent objects, maybe you are creating them incorrectly?
Well if you just drag a model into the scene, then drag it back into the assets to create a prefab, it will actually add an empty gameobject to the root.
But perhaps that is because it has multiple relevant children? Or perhaps it's dependent on the hierarchy of the model?
Strange... Just tested it, it doesn't that for me:
I just tested, it is because of armatures. The basic cube exports like your lantern there
If your model has an armature, it makes sense that it would create an empty gameobject to represent it, as moving the armature would want to move all child meshes.
How to spot a Blender user =D
There is likely an export setting to remove the root armature node from getting exported into the fbx, but I am not sure if you would want to do that most of the time.
Either way, it's a model issue, not a game engine issue
Should I be using scriptable objects to create classes? IE: Using a scriptable items object just as like the constructor for my actual items so I'm not spawning in a bunch of scriptable objects?
use scriptable as immutable (readonly) data
There are assets on the asset store for saving / loading GameObjects and Componentsβasssuming you needed it and didn't want to make your own system for it. They usually cost a decent amount of money though. https://assetstore.unity.com/packages/tools/utilities/easy-save-the-complete-save-data-serializer-system-768 This is a very popular one for example.
So yes then. If I wanted items to be affectable I could create a potion scriptable object that at runtime created the potion class. Then if I wanted to affect it, I'd affect the potions class, not the scriptable object
I got that right?
Yes
Right, scriptable serves as default values. If they weren't available, you'd use plain text or json otherwise
Is there any way to link them easily with classes using scripting? IE: Right now if I had a 'person' class with attributes such as hp, def, magic, I'd duplicate those in the scriptable object for the constructor. Any way to make it so if I added a 'luck' attribute to the person class later on, it'd automatically be created in my scriptable object constructor?
You can write to them, or use them has a single static instance (much like a singleton pattern), but it's probably better to understand why'd you do that over doing it the general way with monos and c# classes
Sorry, I don't understand what you mean
I'm making a 'sports' simulator and the usecase here is so I can quickly create people on the backend. I am going to start with limited statistics and add more as I move forward
I'm just advising writing to scriptable objects as an alternative, because you can overwrite data if you're not careful
which can affect other object instances uses that same data to read from
Ah, I see
In this case, you'd have a scriptable object profile for each person class that serves as the default values; person object* one always starts with 100 hp
and if multiple people play as that person object, they'd all also start with that 100hp default value
Make a struct for the data, then have an instance of the struct in both your Person class and the scriptable object
Ooh that might be it
Remember, you can't use the constructor when initing monos, but you can make your own init methods to feed it the data
So would my struct be like 'stat block' or something, in this case?
you would just do something like this:
[Serializable]
public struct PersonData {
public int health;
public int maxHealth;
public int defense;
}
public sealed class PersonConfig : ScriptableObject {
[field: SerializeField] public PersonData Data { get; private set; }
}
public sealed class Person : MonoBehaviour {
private PersonData m_data;
public void ApplyConfig(in PersonConfig config) => m_data = config.Data; // do other stuff if necessary
}
If you need this to be shared with other things, you would make more generalized names, but this is the idea.
once those stats are in 'preson' are they easily changeable?
yes you just change the copy that the Person has
Can you go in and change individual elements
because it is struct (value type) it will not change the scriptable object
yes you can
like PersonData.health = 5
to disable object use SetActive(true) or (false) SetActive(true) or (false) SetActive(true) or (false) SetActive(true) or (false) SetActive(true) or (false) SetActive(true) or (false)
Im getting an issue I dont understand, using a Physics visualizer for the editor, some dll code is spamming the console with "Look rotation viewing vector is zero" whenever im running by my AI that force them to flip directions to look at me, im not sure what "viewing vector" is actually referring to in the code im using, since not a single axis is 0, but it seems to care about the source.z for some reason (which is also not 0)
bool IsInLOS()
{
var source = head.position;
var target = rayHit.collider.transform.position;
Vertx.Debugging.DrawPhysics.Linecast(source, target, out hit); //produces "look rotation" message
var isHit = Physics.Linecast(source, target, out hit); //perfectly fine
return isHit;
}
If I add new Vector3(0, 0, 1f) to source (as suggested online "just add a small number", but anything smaller than 1 doesnt "fix" it), the spam seems to go away, but then my LOS is inaccurate, head is a bone on the AI's rig, some values are small but not 0, what could be causing this and why does adding 1 or higher "fix" it? Anything more I could investigate? The point of this code is for my AI to use a LOS check from their head to see for example "if theres a wall between AI and player, assume AI cannot see player, otherwise attack player"
my guess would be that source and target are the same
Look rotation viewing vector is zero is basically an error message that happens when you plug Vector3.zero into Quaternion.LookRotation
which can happen if you do lots of weird things like... telling a Transform to LookAt itself or passing V3.zero into Quaternion.LookRotiation or other similar nonsense things
Strange, that makes sense, but I dont think these 2 are the same, I printed their positions before and they were always different but ill double-check if they are the same object, though they shouldnt be (since I use a LayerMask)
well source and target are Vector3s
just print them
see if they're the same when you get that error
Yeah, but those are not an option for me sadly, since I live in a terrorist country and do not have any means to pay online for anything.
damn..
So either something free, or I need to do it myself
God Damn you
Is "the object my camera is looking at" really something you need to serialize/save?
The first step to any save system is thiking long and hard about what data you actually need to restore the game state
who can give me talking tom playback what user says
anything else is not necessary
Well it can be NPC, and NPCs tend to move, so I can't just store the Vector3's of that object position
do you need the exact npc position and orientation etc stored for every npc?
What kind of game is this?
What? No.
Because you have not said anything worth responding to
then you don't need it
think about what you actually need to save
I SAID who can give me talking tom playback what user says
for example - let's take Mario as an example. The only things a Mario game needs to save are:
- the completed levels
- number of stars/coins/points
that's it
think about what your game actually needs
your mother||isfake||
But if I load the game and do not restore that reference, camera will have no object to get position from, if these kinds of links aren't serializeable, so it will stay in one place after I load the save.
Also I take my point back - I do need to store and restore NPC's transforms - they aren't stationary and can (and WILL) be in the different part of the level when player press "save".
i am making talking tom clone just i need a script that make him reapeat what user says
CHAT GPT NEVER HELPED ME AT THIS
Hey Hey Hey Hey
-_-
I guess target.z is 0, but the issue seems to be with source which is not 0, even if I add like 0.3f to z it still causes the messages, anything seem odd from those logs? For context:
Debug.Log(head, head); //source
Debug.Log(rayHit.collider.transform, rayHit.collider.transform); //target
Debug.Log(source + " | " + target);
π
Other such situation where I will definitely need to restore the references would be the AI, so that nPC's wouldn't lose the target they were attacking or going towards when game was saved.
There are other people with problems too
you have to wait for an response
!warn 980625836875063348 Don't spam the channel. See #854851968446365696 on how to ask questions here.
issamiyad#0 has been warned.
anyways, guys i have an slider variable, but my slider doesnt reference with the variable
and it has the slider component
and i put this in the code
idk what's going on
Check that you are referencing the correct type and mixing it up with UI toollkit objects
i am
The inspector in that pic thats trying to reference your slider, is that from a prefab or an object in the scene?
prefab
i got it from an asset
Ah, that might be the issue, prefabs cannot reference scene objects, since theres no guarantee the scene would ever be loaded or the reference would be consistent
so what do i have to do
i mean, i unpacked the prefab
bruh
i got it
it was on the prefab folder π
i forgot abt tht
@trim ferry They are typing presumably answer to your question, have some patience and don't spam
im not spamming? i think
im just telling that i solved it
wait, now that i have put back in the prefab folder my reference disappeared
When you spawn prefabs at runtime and you want them to reference scene objects, have your instantiating script pass needed references to them
ok
Here's the basic example of this https://unity.huh.how/programming/references/simple-dependency-injection
Ok, I will try, but i remember that my last project i made a turret and i got this mechanism right, but i just dont remember how..
This slider looks like a health bar, is your goal whenever something causes health to change (ie: take damage, heal, spawn, etc), you want this script on your prefab to update the slider in your scene?
man
you are a genius
when i was working on my last project, i created a script for UI Managment, you made me remember it, thank you
Since prefabs are sort of ephemeral, I try and avoid doing Dependency Injection on them, and instead approach it upside down.
Instead of injecting FooService into MyPrefab, I have FooService modify the prefab.
Cause 1 service mutating 100 enemies is typically a lot better than injecting that service into 100 enemies individually
I'm having issues with the collision system in getting contacts.
When my player goes very fast, and clips into the wall, the game gives me a contact point (red X) OUTSIDE of both the player and terrain colliders. Why does this happen?
what my code does to generate the green point (coordinate to check) is:
-Get closest point to contact point inside the ground collider
-If normal vector is pointed away from player, flip it.
-Move a bit into object against the normal vector.
but the contact points it gives me are so screwey, I need to do a lot of correction just to get a point that isn't terrible
like... how much logic do I need to tack on to unity engine's basic physics just to find out what tile i'm touching
is this gonna work?
i hope so
Personally, I dont think a UI manager should be attached to the player, I like to make them either have a static reference, or setup a static broadcaster to pass events around without needing calls like Find, if your spawning your player in, you could even setup a static event for when your player spawns that the UIManager listens for
@crude mortar @thin hollow
Hey guys, still not sure if you can get the model and components to be at the root of a prefab.
When dragging and dropping a model into the scene, Unity adds an empty game object as the root, I am not sure if this is normal, I want to figure out it's possible for the model and components to be in a single gameobject.
Any clues? thanks
here's a video of that
With a full Dependency Injection stack I just end up with all my services being POCOs, with a single MonoBehavior as the entry point for Update() that cascades all the way down the tree
And then at the very bottom I have a service that is in charge of keeping track of my prefabs that have been created and acts as the API for managing em and doing CRUD
pixel, I have a big issue with collisions, if you know about how contacts work
For the record though I have over 10 years experience with C# I got about 4 weeks experience with unity :x
My goal is to, on collision, figure out what tile on a tilemap I collided with. Problem: sometimes the contact point makes no sense!
But I think your issue is perhaps continuous collision mode I think it's called?
On your collider I believe there's a checkbox for continous mode or something? It's higher resource cost but handles collisions more precisely for high speed objects
what
Just to confirm can you put a mark or something on the pic where you expect the collision point to actually be?
Aight, and are you hooking into event method or polling on Update()?
event method
I'm testing now, and I haven't gotten any errors since putting im into continuous mode
sry for delay while you're helping. I think you may have gotten it tho
Ah yeh, continous handles "mid frame" collision math
god damnit
ty so much. I would have never figured that out
nothing online covered that
First response for "unity prevent high speed wall clip" gives the answer :3
Coding is 99% Google fu haha
1% suppressing your urge to fall asleep in meetings >_>;
I've been looking for something like that for weeks. ty
I'm mad that the solution was a checkbox, and happy that it was a checkbox
Hey. I've got a question about Jobs. I don't hully understand how to treet them. Are they more like Coroutines in that they will run for multiple frames until they are done? Ore they more like Updates as in they just calculate a single frame? How shell I work with them? I'm asking because I've read that they can't grab deltaTime and needed to be fed deltaTime from the outside. That makes them more like Updates than Coroutines.
jobs is unity version of multithreadings
Why does it equal null?
var provider = gameObject.AddComponent<MonoProvider<T>>();```
What's the error telling you
provider.value = component;
on this line
NullReferenceException: Object reference not set to an instance of an object
Yup, but there are a lot of practices in multithreading. You can start an actual Thread that works infinitelly until you stop it manually, sort of a parallel loop. There are Tasks that work until they are done, which may take a lot of time. Or you can just multithread a single frame, as in spread tasks performed in current frame to multiple threads, but it's still just a single frame. What of all I've described sounds more like Jobs?
the last one, i use job to handle lots of requests at one update
idk is there long running background job since it is quite difficult to transfer data between different jobs and main thread
In Unity.Localization, is there a way to reference an existing string table entry? When I create a field of type LocalizedString, I can't seem to reference an existing entry.
The window should show up after clicking the top dropdown.
GUI Error: You are pushing more GUIClips than you are popping. Make sure they are balanced.
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
ArgumentOutOfRangeException: Index and length must refer to a location within the string.
Parameter name: length
It's coming when I'm getting build, I don't know how to solve it
is that all in the error?
is there a stack trace?
if you double click it does it lead anywhere?
Got it! Apparently you have to type for results to show up... https://forum.unity.com/threads/localization-not-finding-string-reference-in-editor.1295262/
sqlite database is unavailable for users until changes are written in db browser, right?
that's code question
that's a complete nonsense question
why.
read what you have written
I get an error when changing database manually and not writing changes.
SqliteException: The database file is locked
database is locked
it cannot perform any actions until changes are written there
how can you 'change the database' and at the same time 'not be writing the changes'?
I have written "changing database manually"
not via code
it's disposed there
it's performed so that it's correctly disposed
either way, if you are changeing something you are writing the changes no matter how you are doing it
no.
I am disposing database when writing chages via code
if I change table manually, I have to write changes
and when changes are not written, I cannot perform any further actions in code
do you mean commit the changes?
no, write the changes
then you have no idea what you are doing
"write changes", as you can see on screenshot I have sent
are you doing DDL or DML ?
there is an or in my question
both
currently using DML
I am inserting data in the table
so when you use DML to make changes to an SQL database you have to commit those changes to makes them fixed
I have mentioned that they are commited via code.
If changes are done manually, you have you commit them manually too
and while they are not commited, I cannot run my script
that's what I am trying to say
it does not matter how you make changes the mechanism is the same
yes, but they are commited via code when using closed using
It's always committed via code, just not your code when you do it manually
yes, I have to save them when I do it manually
also it seems than running 2 examples of this code causes an error too
but I cannot test it
because I don't know how
I can just test running it via code and manually
which would tend to suggest that you open the database for exclusive use
I am sorry, I don't get it
SQL databases are multi user.
when one user changes something using DML those changes are visible only to him until he issues a commit.
If you have 2 processes which are locking eachother out then you must have the database open for exclusive use only
I see, I'll look into that
thank you
From what I remember yesterday, you said this was for users saving levels right? You ideally dont want users to even have direct access like this anyways
of course I don't want
I don't mention saying that I want them.
but what do you even my by direction access?
Then there should just be 1 thing writing to the database anyways
I will just add levels into database when they save them
what if 2 users have created level simultaneously?
Neither user should have direct write access
You'll quickly get people writing bad things, or just spamming to fill it with a million entries
yes, of course.
You can I even come to idea to make them able to change that.
I want to change it via script when they save level
doesn't really matter because SQLite is not a server viable database anyway
they will just create level with my game
and when they click "save level", I have to load that level to database
ideally to their profile
anyway, I think I should make databases for more than 2 hours
I gonna look into that tomorrow, thank you both for your help and time
I have a TickManager, which can have various ticks, like music (qtr, half, etc). One of my entities needs to change it's tick on the fly based on it's state. So my question revolves around the tick actions it subscribes to. Should Actions only be subscribed to once (like in OnEnable)? If I set Manger.Instance.OnTick += TickAction every Tick (via a SetTick method), would it subscribe more than once?
not entirely sure what you mean by the first part of the question, but yes it will subscribe more than once if you keep adding it
Okay, then that means I need to change my approach for an entity that needs to switch between two tick actions. I'll just subscribe to both in OnEnable, and put the logic for Tick type with it. Thanks.
I initially thought something like this would work, but instead, I'll just subscribe to both, and put logic for which Tick to do.
protected override void OnEnable()
{
SetTick();
}
protected override void TickActions()
{
SetTick();
// do some other tick stuff
}
private void SetTick()
{
if (_baseEntity.IsPowered)
{
TickManager.Instance.OnEighthTick += TickActions;
TickManager.Instance.OnQuarterTick -= TickActions;
}
else
{
TickManager.Instance.OnEighthTick -= TickActions;
TickManager.Instance.OnQuarterTick += TickActions;
}
}```
each entity can keep track of which one its subscribed to (like which interval its running on) then just unsubscribe from that, while subscribing to the one you want
doesnt even matter as well if its not subscribed before trying to remove it
https://dotnetfiddle.net/JA6TYy
subscribing to both will still require you to keep track of which interval its running on, so might as well just subscribe to the right thing rather than subscribe to all and ignore the ones u dont want
yes, but if, for example, IsPowered is false for X ticks, will it then start running TickActions X times per X tick? (since in my code case, it would subscribe to the same action every tick)
oh i just noticed that you are calling SetTick() inside the other functions, yea u really dont want to do that
im confused as to why you need that inside TickActions()
I don't necessarily. I was initially asking if it would subscribe more than once. Since it will, that means I need to only subscribe once to both in OnEnable, and remove SetTick altogether, then put logic within this file (either separate TickActionMethods or something) to know which tick action code to run.
you dont need to subscribe to both is what im saying, because that logic for "know which tick action code to run" can just be applied to subscribe to the correct delegate. Instead of calling SetTicks() everytime, just only call it when you need to actually change how its tick system
if the tick system hasnt changed, you dont need to call it
In other words, in SetTick, just add a condition to check the last tick state - so it won't up the subscribes each tick.
no, just dont call SetTick if you dont need to
if the condition for swapping tick systems is isPowered being changed (true/false), then everytime its changed, subscribe to the correct delegate
you could even make this a setter, if the value has changed then subscribe/unsubscribe. If it hasnt changed, do nothing
Using SOs you wouldn't need the switch statement at all
that depends
how different is the behavior
Let's say the difference in behavior is that one enemy waits 10 seconds before attacking and the other waits 5 seconds
that's easily expressed as a variable
They are not mutually exclusive
For example I made a tower defense game
I use switches a bunch, especially for my ability system I've been making. If it's just a one time instantiation of data I don't think it'll matter that much.
my towers are defined by ScirptableObjects
things like Range, rate of fire, etc. are easily expressed as normal variables
things like "targetting strategy" are enums
and for those enums ultimately a switch statement is choosing a delegate to use to determine which target the tower will prioritize
actually I guess that's not inheritance π
Yeah, but then you run into stuff like firing modes, like does it fire in a random range, or is it a fixed value
sure and unity's particle syustem is a good example of how to handle that
im not too sure how it's handled under the hood
I expect it to be a billion bools like the gui itself lol
you can reference the SO from anywhere
yes
use it in multiple places
make a list of them
reduce the numnber of prefbs you have to manage
they're useful for caching a single instance of data to read from
Hi, not a code question but not sure what the correct channel is. Using unity recorder to take a screenshot and I don't have an alpha checkbox. This should only be excluded in GameView or JPEG format so any help would be appreciated.
nevermind, just used photoshop. Not as clean and I'm going to leave the previous message as it may be a bug?
Is there a way to push a nav mesh agent?
Everytime I addforce to itβs rigid body it just freaks out and shakes a bunch
all you need is a reference to the agent then do agent_Ref.destination = the_Vector_3
I think they want a physics reaction, like knockback.
@storm copper , you'd probably have to disable the agent first, then reenable it after the addforce
ahh my bad
!vrchat
Join the growing VRChat community as you explore, play, and create the future of social VR! https://discord.com/invite/vrchat
!cdisc
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
!docs
Ok thank you I will try that
Hi, I was just working on my project when I suddenly started getting this error message?
UnityEditor.Graphs.Edge.WakeUp () (at <646995db22024662a460758c77558643>:0)
UnityEditor.Graphs.Graph.DoWakeUpEdges (System.Collections.Generic.List`1[T] inEdges, System.Collections.Generic.List`1[T] ok, System.Collections.Generic.List`1[T] error, System.Boolean inEdgesUsedToBeValid) (at <646995db22024662a460758c77558643>:0)
UnityEditor.Graphs.Graph.WakeUpEdges (System.Boolean clearSlotEdges) (at <646995db22024662a460758c77558643>:0)
UnityEditor.Graphs.Graph.WakeUp (System.Boolean force) (at <646995db22024662a460758c77558643>:0)
UnityEditor.Graphs.Graph.WakeUp () (at <646995db22024662a460758c77558643>:0)
UnityEditor.Graphs.Graph.OnEnable () (at <646995db22024662a460758c77558643>:0)```
And now my player character isn't detecting when it collides with an enemy hitbox. (Player character's collider is a 2D Polygon Collider, enemy hitbox is a 2D Box Collider)
Oh, no it is detecting when it collides, but it won't play the hurt animation.
Hello, I've started a little game a while ago but had to take a break because of an annoying problem, which I still cant solve. Its about a currency, that you pay in the ingame shop to buy character packs, but my code that checks if this currency is 1 or more doesnt do as it should. The currency amount just goes into negativity and the player can buy infinite amounts of packs. Im using a datahandler, that saves the data in a file and I think the problem is, that somehow this data doesnt get updated in time and still thinks, that the amount of currency is the one it started of with, not the one it is after being used.
For code reference, please ask, because theres too much to simply paste in :) thanks for the help!
this is just an internal unity editor bug. It won't affect your game
Share your code if you want help
!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.
Ah I got it working
hi! Does anyone know how to fix this error "Error building Player because scripts had compiler errors"? I was trying to build the game. What I read online is to move any script that has unityeditor in it to an editor folder but how do I even find out which scipt has it without opening one by one. Any ideas?
What do the errors in the console say?
bottom bar in unity
click it to open the window
the errors in the build will tell you exactly where the issue is.
All it says in the console "Error building Player because scripts had compiler errors" is there a way to access more detail then the console anywhere? It is not specific at all
There should be other compiler errors listed
All I see is this:
look at the one right above that lol
it tells you exactly
Do you think that one is the issue? It has nothing to do with the player
of course it is
yes
Hey I will take it haha
very obviously so
UnityEditor code doesn't exist in the build, you cannot use it outside of editor contexts
so do I just move that script to an editor foflder?
When it says "Error building Player" it means the Unity Player aka your game. Not the Player object in the game
ah!
doubt it - that's probably an essential script for the game if it's called "PressurePlateScript"
Regardless of that, it's an error, a compiler error, exactly the type of thing it was saying was the issue
you need to remove any reference to UnityEditor stuff from it
or wrap UnityEditor stuff in a preprocessor directive
Presumably there's no good reason for it to be using UnityEditorInternal
yeah I'd guess it was added by accident
oh so just remove that "UnityEditor" line?
hopefully that is it. It was calling "// private void Update()
//{
// options = UnityEditorInternal.InternalEditorUtility.tags; // Get all available tags from the Editor
// }" so I just commented it
that is the only place I saw UnityEdtor mentioned
yes that seems likely
thank you! well it has been .48 seconds and it is still going so that did fix something. thank you very much!
It's not ALWAYS the case, but I try to solve errors from top to bottom (which is chronological order), because often one causes the next. Even if they seem unrelated
ah I see! I didn't know that! thank you for the tip!!!
oy lads, i've got a script that gets added to an object the player has picked up, and i'm trying to have it instantiate another object when it collides with a trigger. my struggle is getting the reference to the object that i want to spawn when the script doesn't start on the object that gets picked up. is there a way to do that?
Why are you adding a script to the picked up object?
How would you like to determine which object should spawn when it collides?
Can you just reference the prefab from the pickup script on the player and propagate it from there?
- so i can have the object check for a collision, and only that object check for a collision. i figured it would be bad practice to have several trigger objects all check for the same collision.
- if i can figure it out, i want to do that via code. like how you can do
GameObject.Find("dadada") - possibly, but i'm trying to see if i can do it without adding more to the player's scripts. what i'd like to do is just have the player add the script to the object, and then the object will decide what object to spawn based on what it collides with
how can i change the width of an image (in pixels) via a script?
like :
myimage.width = whatever;
- is confused, When you said "gets added" did you mean in code, or on a prefab? I assumed the former by the wording, but that wouldn't help with what you're saying. What does the first line in your first point mean?
- I'd recommend having a script on the pickup object with a prefab to instantiate instead of finding it. But that IS how you find (https://docs.unity3d.com/ScriptReference/GameObject.Find) things. You need the exact gameobject name
- Maybe add it to the object being picked up? Then the player gets the trigger event, checks if the object has that script and calls the spawn method from the script?
Can somebody help please? I've read the https://docs.unity3d.com/ScriptReference/SerializeReference.html
but I can't quite still understand it... Suppose I have a custom struct that has a reference to a Scriptable Object asset in it (in this case - one that stores data for items properties in the inventory component):
public struct InventoryItem
{
public string id;
public ItemDefinition def;
public int amount;
}
Do I need to mark def variable of struct with [SerializeReference], or I need to mark the whole struct, or it's all fine actually and I do not need it?
Please don't cross post
thats not what SerializeReference does
by default unity will serialize anything that is not UnityEngine.Object by value
so if you need to serialize a reference to a c# object you use that attribute
ScriptableObject already is serialized by reference since its a uobject
Ah, okay thanks!
-
correct. the script gets added to the object via code from somewhere else. i have a player object that can pick up an object that it's looking at, and when the player picks up the object, it adds a script to that object.
-
using that command only works for active game objects. that's just an example of what i'm trying to do. i thought maybe there was a similar function that does that, but just finds it in like, the assets folder. i'm trying to spawn an object that doesn't exist in the scene, and if possible i'd like to avoid storing references to these objects in the player's scripts just to pass it along to another script. i just want to see if i can do it another way.
-
that probably would work, but i'm trying to do this object spawning from outside the player object.
simplest way is to have a singleton scriptable with references to whatever assets you need
but since it will require that scriptable to be in Resources, it will lead to longer startup times
- I didn't mean do you want to do it via code I meant... how are you deciding? Is it a property of the player? Is it due to some weapon equipped to the player? From a gameplay perspective what determines which thing should be spawned?
my bad, misunderstood the question. the thing i'm choosing to spawn is determined by the trigger the object collides with. ex; if i have the object collide with a door that has metal door hinges (with triggers on those hinges), i want it to spawn a particle system thing i've made to look like sparks have gone flying
think that answers the question better
i'm able to check for the collision with that specific type of trigger, so i know that part works properly. it's just getting that particle to spawn that i'm having trouble with
can you get a NullReferenceExeption while setting a variable
show the code that throws
points[i] = new Vector2(Random.Range(0,width), Random.Range(0,height));```
yes array can be null and you are not setting a variable
you are accessing the array indexer
[] < indexer
which is a method
ty
shouldnt that be a index out of range exception
nothing can throw it if the array is null
ah true
you put put a component on the door that has a reference to the sparks prefab
basically a "COllideWithMeParticles" component
that goes on these various objects
Clarification, same goes for references to a prefab in assets (for spawning those), right?
that's a big brain solution. that way i could do something like desiredParticle and just have that be different for each object. then the object that spawns the particles can spawn whatever that variable references
yep
and all you have to do is throw that component on the object and forget about it
and the projectile script just looks for that component and spawns whatever
reference to gameobject, which is also uobject
anything extending UnityEngine.Object is considered an asset that can be written to disk, and has a guid/local id
which is used to serialize it and retreive it
i literally said it was affecting my game thoughπ
like its whatever, i restarted my computer and now everything's fine
but it did affect my game
that error was unrelated to your game at all. it was specific to the unity editor, you most likely had the animator window or some other graph editor window open
look at this monstrosity of a nested process
Please cache things instead of repeatedly accessing them 
well.. maybe if i leave it in the corner and pretend it never happened 
that's what i always do
a good example is my special multi-type list class
it's probably 1000 lines of code
Or just spend the 10 seconds it takes to refactor the repeated access away
Got a problem with rounding. Theese are different chunks. with my current code i take the worldPosition/chunkssize(21 in this case) and get the chunk. It works most of the time but in one senario when I am pressing chunk 2 at the line neghbouring chunk 1. I get the pos .5, 10.5 with the mathf it becomes chunk 0,0 but it should be 0,1.
The math makes .5 position to 0.02 that's rounded to 0. While 10.5 becomes .5 that should be rounded up but rounds down to 0
wow, upon measuring it it's like 3x or 4x the scroll length
i was actually unsure on how to even work around this but as long as it works 
Ok. Did you have an issue you need help with?
nope
Okay
please
oh, in this specific example i was actually working with nested classes where their types differ,
so like in a World i contain a bunch of Continents and in a Continent i throw some Regions etc
why does that matter at all
i could just make an access func to make it more readable
the indexer is the access you are repeatedly calling
i would have to do like MapWorld[i].MapContinent[j], not sure how to store that like shown above
you don't need to access MapWorld[i] 15 times, you just have to do it once
https://docs.unity3d.com/ScriptReference/Mathf.Round.html
the docs explain what it does at 0.5
but the access func would definitely work
oh so i just cache it into something called mw to make it fast?
sure lemme pull that one
although the monstrosity looked nice too
Just get your IDE to create the variable (if it can do that). If you don't know what type it is, you can manually just write var, and your IDE can definitely convert that to an explicit type too.
oh, my IDE's raw
it's been raw forever so i'm used to it though
like, nothing's setup
Jesus christ

Well, do note that you can't ask code questions on this discord if you have an unconfigured IDE, because it's completely disrespecful to people's time.
i understand
on another note, how's this looking?

don't think it compresses any further
way more reasonable
yeah i think i like it better now
think i'll avoid monstrosities like before as much as i can from now on
even if they get tucked away anyway
what's the proper way to hold references to a bunch of prefabs that will be used some time in runtime? It feels like have a [SerializeField] list on a random script isn't the best practice
Nothing really wrong with it tbh
What do you mean by used some time? Like there's a chance they won't be used at all?
they're used for creating base level on start, and then when the game restarts used again
That seems fine. If you want to have different "sets" that might make things easier to organize, maybe use ScriptableObjects instead?
I'm assuming the number of prefabs is large
lets say I wanted a spaceship like the one in Cosmoteer
as in its made of a ton of tiles that can disconnect and float freely when whatever is connecting are destroyed
also the whole thing should act as a physics object
what would be the best way to do this?
could I use physics2d and link all the tiles together when the ship is spawned
or is there a better way
Is there nay help chat here?
These channels are meant for coding questions, so ask away!
how do i make the door not cast shadows on the walls?
i want the door to only cast shadows on everything except the walls
[System.Serializable]
public class MapScene
{
public bool isTown; // if this is True, then show the variables below
public Vector2 spawnCoords; // when you open your save and load the game, you spawn here!
}
Hello! I was wondering how the above could be done! I remember seeing it somewhere, forgot where though, maybe in SpriteMask Components?
If isTown is true, then in the Unity Editor itself, in inspector it'll show the variable spawnCoords, otherwise it won't
it's purely visual but is still nice to have!
thank you very much!
Hey there. Not sure in what channel multiplayer help goes but ill ask here;
My syncing isnt looking right. I am using the Relay system with Untiy's netcode for GameObject
The players stay up in the air for some reason.
#archived-networking would be your best bet
I'll try there, thanks!
Multiplayer discord also a good shout
Hello, i wanted to add this data to store in a scriptable object but it doesnt show in the inspector is this type of data possible to implement in scriptable object? if so what did i do wrong? Thank you all for your help,
or is there a better/correct way to do this? please let me know π
Try marking the PerWave class as serializable, using the [System.Serializable] attribute
Also if you're planning on using the PerWave class outside of WaveData, it should be in its own file
Shader "Example/TestShader"
{
SubShader {
Tags { "RenderType" = "Opaque" }
CGPROGRAM
#pragma surface surf Lambert
struct Input {
float4 color : COLOR;
};
void surf (Input IN, inout SurfaceOutput o) {
o.Albedo = 1;
}
ENDCG
}
Fallback "Diffuse"
}
Why does this default surface shader turn pink?
Ask in #archived-shaders
sorry π«‘
Add the system.seriable
Thanks, works like a charm, one more question tho, can i use Dictionary in scriptable Object? i tried using System.Serializable it doesnt work
you can however use 2 lists/array
Alright, feel like I am going insane on this one and I've been up all night working so could use a 2nd pair of eyes. As seen in the screenshots below, I am using a PerlinNoise generator to display on to a dynamically rendered mesh, however, although the PerlinNoise can accurately take in the size parameters of the mesh, when applying the noise to the texture of the mesh, it only shows 1 section of grey noise and not the entire thing.
Code snippets also, probably somewhere I am just not applying the X and Z correctly.
Have you set UV for each vertice? If every vertice has the same UV, then everything will have the same color.
