#archived-code-general
1 messages · Page 355 of 1
bruh, try it and see eh?
ide is suggesting about keycode 
Yup it works, but like, how do i disable it for y axis lol, if i look up, i go flying
sooo.. ur forward axis points up
only change the X rot on the camera
then dont rotate the chracter up?
cinemachine has a built in TPV camera why dont you start with that?
all you do is rotate the target up/down on X of camera
Huh? I dont think ur getting, Look, that code adds force to direction where player is looking, now i want this to affect the X and Z axis, meaning that if i look at Z it moves towards Z, and If i change my X roation or view, it adds force to X, but if i change Y axis, i dont want it to move up or follow or react with that change of view in Y axis
Rotating on Y axis implies your rotating shoulder to shoulder
Rotating X is pitch
if ur pitching your character Up then you are flying up because of relative velocity in forward
typically you setup.
Camera = only rotates X (pitch using mouse Y)
Character = Rotates only on Y (using mouse X axis)
alr alr
well ig in third person view you dont have to use mouse to rotate char
if you go forward using the camera's forward relative velocity thats ur issue, use character's instead
no i mean my movement script and do tween in start() works but in update doesnt
you haven't shown your code for that so it's very hard to say why
most character are set up like this
ur players body rotates left and right.. (this is the axis u'd use for direction)
the camera rotates left and right b/c its a child of the player..
but it rotates up and down locally
so no matter if i look up or down.. the player object will still be facing a direction thats parallel to the floor
using System.Collections;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEngine;
public class PlayerCoreConfig : MonoBehaviour
{
public Transform Core;
public Transform Player;
public float speedMP = 0;
Rigidbody rb = FindObjectOfType<PlayerMain>().rb;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Core.position = Player.position;
if (Input.GetKey("d")){
rb.AddRelativeForce(Vector3.right * 15 * speedMP);
}
if (Input.GetKey("a")){
rb.AddForce(speedMP*-50*Time.deltaTime, 0,0);
}
if (Input.GetKey("w")){
rb.AddForce(0,0,speedMP*50*Time.deltaTime);
}
if (Input.GetKey("s")){
rb.AddForce(0,0,speedMP*-50*Time.deltaTime);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMain : MonoBehaviour
{
// Start is called before the first frame update
public Rigidbody rb;
public float speedMP = 0;
public Transform player_position;
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
I know i made a mistake
i cant locate it
use the links for large code
mb dint know, btw, PlayerConfig is an empty Object
Rigidbody rb = FindObjectOfType<PlayerMain>().rb;
why
just make a field in the inspector , put the script ont he same object. why do this
Uhh ok so look, the Rigid Body is a ball, so it will rotate like a ball, which means like
Uhh its gonna be ahrd to explain, i have to type a lot
just hang on
there is so much wrong with this code
you NEVER add time.deltaTime to AddForce, also rigidbodies should be moved in FixedUpdate
are you just guessing this or
{
Core.position = Player.position;
Vector2 input = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
Vector3 force = new Vector3(input.x, 0, input.y) * speedMP * 50;
rb.AddRelativeForce(force);
}```
jus saying
remove time.deltaTime and its correct
oof
So Since its like a ball, when i directly add force to the ball, it will rotate, which means (with refrence to photos) it will turn from picture 1 to picture 2 and like this AXis will be randomized, which means the forward will sometimes be down, sometimes up, sometimes right and left, so for this, i need a core, that doesnt rotate when the ball rotatesfor which i use the playercore, which means it will add force in direction of pointing to playercore
thanks mate..
i also had this problem with my enemy rotating with its floating sword but after trying to fix it i ignored it
AddForce will still wait for the Fixed physic step to apply the value so its already good to go
consistent
yea yea, ofc..
yes, we understand
why not just lock its rotations?
u can still move it around.. w/o needing it to rotate..
i want it to rotate
heck ya 🥳
it has a cool effect
its a solid color..
u cant tell if its rotating or not
for now
ahh ok ok
so this is the only logical thing my racoon brain could ocme up wiht
interesting.. not gonna be a clear-cut solution for that
gameObject.transform.rotation = Quaternion.Euler(0,180,gameObject.transform.rotation.z);``` this is very wrong
oh
use the camera for the correct movement directions if u can @swift falcon
so quaternion. what?
yes
@swift falcon
Vector3 projectedDirection = Vector3.ProjectOnPlane(Player.TransformDirection(moveDirection), Vector3.up).normalized;
shut up
no memes
mb
if u project the direction to a plane.. using the Vector3.up direction
ok so what do i do with this
but not only plain
it makes the direction perpendicular to the ground
it doesnt matter..
the plane is imaginary
it just level w/ the horizon since we use Vector3.up
ur forces would end up like this
still problems
solutions
bruh delete using System.Numerics;
wrong file probably
pay attention to your errors
they have words in them
Double-click the error to navigate to it. They should be clearly visible (underlined red) in the code
you can read the words and get information
yep, looks like a simple problem you should fix
sounds like you're too busy to learn to code
mb
The code Spawn posted is an example, it is not meant to be copy-pasted blindly, you should adapt it
im too overworked
alright
now what
Im gonna slep
drop ur stuff here now
problem is dotween is not allowiing anything to change rotation so basically its doing "transform.DORotate(new Vector3(0,0, ZRotateTo), 2, RotateMode.Fast)" so its not even flipping
is there a way to make public floats null?
Now... projectedDirection is the player's forward direction projected onto the world x/z plane, such that it's not pointing up or down anymore.
I'm not sure what you were doing with that 🤷
yeah... i mean
why are you using DotTween if you don't want DOTWeen to control the rotation
You haven't even explained to anyone what you are trying to do
What is your goal?
here you can see what im trying to do
you can see in the video that my player is slowly rotating up and down
when i turn on dotween spin script
its a small rotation but it kinda makes the player look like he is flying
your problem is you're trying to do everything with one object
put your sprite on a child object
and do that little animation on that child object using Local Rotation
Do you mean setting a float to null in general? Public has nothing to do with that
Leave the parent object to do the main player movement/rotation
ok ig i can try that
by default value types cannot be null no.
alright
They can be nullable.
Just change the type to a float? or Nullable<float>
I was just confused what the public has to do with it
I dont think nullable value types are serializable by Unity
nope
Quick question, i added a parallax script to the BG objects in my scene, with each layer having a parent object for grouping, and I attached the script to the parent objects, but I get an error bc its trying to access a Sprite Renderer that isnt on the parent even tho it is on the Child Objects, why isnt it picking up the Renderers?
they were actually asking "How do I make DOTWeen not do anything"
why should it "pick up" the renderers
either your code is assigning them or you assigned them in the inspector
and you did one of those things incorrectly
that isn't helpful
you'd need to show your code
and/or how you assigned the renderer
and please don't take a photo of your screen
public class Parallax : MonoBehaviour
{
private float _startingPos;
private float _lengthOfSprite;
public float parallaxAmount;
public Camera MainCamera;
// Start is called before the first frame update
void Start()
{
_startingPos = transform.position.x;
_lengthOfSprite = GetComponent<SpriteRenderer>().bounds.size.x;
}
// Update is called once per frame
void Update()
{
Vector3 position = MainCamera.transform.position;
float temp = position.x * (1 - parallaxAmount);
float distance = position.x * parallaxAmount;
Vector3 newPos = new Vector3(_startingPos + distance, transform.position.y, transform.position.z);
transform.position = newPos;
}
}
here
No, you'd have to make a wrapper class like Nullable<> that does something similar
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
whoops
how do i make it only affect a specific axis
again, move the local rotation of a child object
public class Parallax : MonoBehaviour
{
private float _startingPos;
private float _lengthOfSprite;
public float parallaxAmount;
public Camera MainCamera;
// Start is called before the first frame update
void Start()
{
_startingPos = transform.position.x;
_lengthOfSprite = GetComponent<SpriteRenderer>().bounds.size.x;
}
// Update is called once per frame
void Update()
{
Vector3 position = MainCamera.transform.position;
float temp = position.x * (1 - parallaxAmount);
float distance = position.x * parallaxAmount;
Vector3 newPos = new Vector3(_startingPos + distance, transform.position.y, transform.position.z);
transform.position = newPos;
}
}
better?
Your code is just doing GetComponent<SpriteRenderer>(). When you call it like that it's going to check if there is a SpriteRenderer on the SAME object as this script
as per this image, there is clearly not a SpriteRenderer on the same object
so it fails
case closed.
ok but its still not flipping
is it because the Xrotateto and the yrotateto arent assigned and are 0
that stuff should be completely irrelevant to any "flipping" if you moved the little wiggle animation to a child object.
because my sprite is a child the y axis is changing
the y axis of the child should never change
well its changing
again, you should now be modifying local rotation
sounds like you're not doing that
you're probably still modifying its world space rotation
as I said here
wait soo movement script of player should be local instead right
no
movement script is no longer relevant
we're talking about the child wiggle now, correct?
your movement script was fine
where do i adjust local rotation?
the tweening script?
whatevewr script you want to use to do the local rotation thing
ok so tween
so transform.DOLocalRotate(new Vector3(XRotateTo,YRotateTo, ZRotateTo), 2, RotateMode.Fast)
yo it works
thank you so so so so so so much
i just did
DOLocalRotate
fixes everything
yeah, because that actually does local rotation
thanks
Is this the following code to get the pitch "pitch = Vector3.SignedAngle(new Vector3(0, dir.y, dir.z), forw, Vector3.right)?"
AssetDatabase.OpenAsset(savedPrefab);
i kinda did it this way
not sure if it's not gonna cause bugs
thanks anyways
I think this is used for textures but what are you making by this code.
Ok.
don't ask why i'm not sure myself if i need it
I never did that too.
hey, does anyone know if there's a way to use transform.forward with a Vector3? i'm moving my character with Rigidbody.AddForce(desiredForce), but im trying to implement moving in the direction the character is looking in.
public class PlayerMovement : MonoBehaviour
{
// COMPONENTS
Rigidbody rb; PlayerInput pi;
// INPUT
InputAction moveAction;
// MOVEMENT
Vector2 moveVector;
float speed = 8f;
Vector3 desiredForce; Vector3 desiredVelocity; Vector3 targetVel; Vector3 _currentVel;
void Start()
{
// COMPONENTS
rb = GetComponent<Rigidbody>(); pi = GetComponent<PlayerInput>();
// INPUT
moveAction = pi.actions.FindAction("Movement");
}
void FixedUpdate()
{
desiredForce = ((rb.mass * desiredVelocity) - (rb.mass * rb.velocity)) / Time.fixedDeltaTime;
rb.AddForce(desiredForce);
}
void Update()
{
moveVector = moveAction.ReadValue<Vector2>();
targetVel = new(moveVector.x * speed, 0f, moveVector.y * speed);
desiredVelocity = Vector3.SmoothDamp(desiredVelocity, targetVel, ref _currentVel, 0.1f);
}
}
i tried using addrelativeforce but whenever i moved while rotating, the player kinda flew away at astronomical speeds
if you want to change the rb to a specific velocity you can just set it
see, i was gonna do that but wouldnt that make me unable to use external forces?
like if i applied an explosion impulse, if the player was moving wouldnt it just do nothing
yes, but you are also overriding the velocity through your force calculations
so you cannot use external forces, since you are not respecting them
wait yeah
it seems to me you're approach tries to mostly eliminate the whole point of having force simulation
you'd typically just add a break / acceleration / steering force of magnitude X with X < mass * speed (and maybe scale that down the closer you get to your target velocity). You would not actually attempt to correct with a massive singular force that changes the velocity in one frame to a substantially different new one.
alright, then does addrelativeforce actually work with regards to a gameobject's rotation?
it uses the rb's coordinate system, i.e. its local space
that is position and rotation
alr tysm 🙏 really helpful
does particle systems throw an event after playing and when all particles died? I want to make a Particle system pool
Does not look like it, no.
https://docs.unity3d.com/ScriptReference/ParticleSystem.html
You could check if ps.time >= ps.totalTime
Or do a coroutine and waitforseconds the total time
yea Im currently doing it via coroutine and IsAlive
would have been nice if there's an exposed event tho, or an official PS pool by unity at least
if you use VFX graph (although its already more performant than particle system)
https://docs.unity3d.com/ScriptReference/VFX.VisualEffect-aliveParticleCount.html (can poll this in update)
Hi! I'm making a 4 key rhythm game. However, i've been stuck on getting the game to recognize when you've hit a note in the correct amount of time. I've been trying to figure it out for a while and its something thats put me off wanting to work on it. Can someone help me wrap my head around a way i could implement this?
Here are some scripts that might be useful
The parser that parses the beatmap files (probably not important but just in case):
https://paste.ofcode.org/kn6TnL6CbJHXMfkwtDe8qQ
My current input method (messy and doesnt work lol):
https://paste.ofcode.org/8YBNbVFS6v4xsRQEHgPSRb
The script that actually spawns in the notes:
https://paste.ofcode.org/32BSkCknG4GxDs5fhqJJTGg
If anyone could help out with this it would be greatly appreciated as it is the main hurdle im stuck with right now
how can i rotate and object around another object by a specific amount?
yea i am in the docs right now
trying to figure it out
it is just rotating infinitely even when i put the angle to 1 the angle acts like the speed not how much i want it to rotate
sounds like you are calling that method every frame instead of only when you want to rotate
ok i solved it
Does anyone know how to get GetPixelBilinear to work?cs Debug.Log($"{heightmapTest.GetPixelBilinear(2000, 2000)}"); Debug.Log($"{heightmapTest.GetPixelBilinear(4000, 4000)}"); Debug.Log($"{heightmapTest.GetPixelBilinear(6000, 6000)}");I get the same output no matter where I sample from. I've tried turning compression off, but crunch compression is turned off either way...?
all 3 of those lines sample the same point. Did you look at the docs?
I put a Time.timescale into one of my UI codes would it be a better idea to place it inside of a game manager file and to reference the ui code into the game manager
What's a good way to get the Player reference on each Monster when it spawns, so the monster can check if it's in range of the player to attack?
Is this where you use FindWithTag?
My game will eventually have multiple player characters, so I can't make it a singleton
Or do I add like a static game manager that has the reference to all the player characters that I can access from each monster?
why not use a physics query like an overlapbox instead? then you don't need a direct reference to the player, you just check if any of the detected colliders is the player
I'll look into that, first time I do something like this
What type of physics query is simplest/easiest? It's a very simple 2d game where the player is static and enemies just move from the right to the left towards the player
I might want to add ranged enemies too at some point
whichever one is the shape you would like to check
there is no separate difficulty level for calling different methods that do similar things
you do realize i literally gave a suggestion as to what would be an appropriate option, right? but again, it entirely depends on how/where you want to check and the behavior you are attempting to create
but again, it entirely depends on how/where you want to check and the behavior you are attempting to create
yeah 🙂 I think a simple ray cast is probably best then
it's comparable to a 2d platformer, but without jumping lol
and no objects/obstacles in the way either
a raycast works if you already know what direction you want to check in. it does not if you are simply trying to determine if any player is within range in any direction.
monsters just move left towards the player (this never changes, nothing blocks them)
and attack the player when they get in range (melee or ranged)
yeah so raycast is perfect in my case then
I always assumed raycasts where something expensive & difficult
no, raycasts are incredibly cheap
perfect 🙂
if you keep helping me like this I'll have to end up giving you a share of my profits lol
Won’t be awake much longer but I just realized I can ask here… been trying to wrap my head around the idea of getting the distance of two objects and applying that distance to another object, scaled and rotated. The idea is to compare the position of each player against the camera that’s at the center of the level and use that to place their nametag on a realtime map elsewhere in the scene to align each player’s name tag on the map. It’s for a multiplayer game I’m doing.
I dont really see what the camera has to do with anything here but this sounds like a simple remap. Like getting the players location relative to the whole area and then remapping that value onto the smaller map
I figured since the map is a UI image displaying a renderTexture, then I could use the camera object's position and re-apply relative to the map's position since the map center should be the camera center
camera is orthographic and the map itself is a square, but it seems like the scaling applies lesser in the Y direction than the X somehow and I don't really understand how that's possible
so more or less the question is if there's any glaring issue with the code I posted that could explain why my scaling seems wildly dysfunctional 😅
Any insight or suggestions would be appreciated!
also sort've confused as to why I had to go for 90 + 45 degrees on the rotation in order to even get it to align with a map that's just on a wall, but maybe I just don't get the math complexity
honestly a lot of this looks like magic numbers
the 0.03 scalar, this seemingly random euler angle rotation, and subtracting -0.15f from the z on the vector
😬 yeah I have no clue how to approach this. I have an inkling I should be using TransformPoints to correctly find and translate the differences in world space…
Isn’t it setting the z to -0.15, rather than subtracting
ah sorry yes its setting
What happens if you get rid of the 3 things that bawsi said
Yeah that was the point but it still didn’t really work right, it’s like 6 or something instead of the number I’m setting it to, which is definitely just an issue of transform points
ok well getting rid of it just doesnt magically solve anything. im just pointing out that its really hard to suggest much because a lot of these numbers are magic and we dont know why you need them. Other than they just work because it was hardcoded in
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.left, 10, layerMask);```
Why is this still hitting things not in my Characters layer?
Euler rotation is what rotates it and places it on the wall, so it would just not be rotated. The scalar is shrinking it from being the size of the playing field to the actual map size, and the -0.15 is an attempt to align with the Z of the map
I was just curious what they did, so doing this could help
because the layer mask includes every layer except the Characters layer
In the map’s case, which axis is z
Away from the camera?
I double checked and Z is the map’s normal vector, essentially. It would go out from the wall
Ah ok
The point of the Euler rotation is that the camera is a top down way out somewhere but I need to translate that relationship to be on a wall
you would usually use some vector projection to translate a vector like this
Honestly a googleable phrase means millions lmao, if you’d care to explain feel free
its somewhat hard to type out what it means, diagrams from online will be a lot better
Is that projecting things onto a bigger/smaller surface using vectors
Like if you moved a flashlight away from a surface (the light cone gets bigger)
That sounds like more what I wanted. The above code definitely tries to do that too but it’s a lots more rudimentary heh, thank you for a new direction for tomorrow!
Hopefully I remember to ask here sooner next time I get stuck
Debug.DrawRay(transform.position, Vector2.left * 100, Color.red, 10, false);
can't get this to work either
You'll want to remove the bitwise NOT (~)
yeah I fixed that 🙂
Wikipedia has some helpful formulas:
https://en.m.wikipedia.org/wiki/Cone
A cone is a three-dimensional geometric shape that tapers smoothly from a flat base (frequently, though not necessarily, circular) to a point called the apex or vertex.
A cone is formed by a set of line segments, half-lines, or lines connecting a common point, the apex, to all of the points on a base that is in a plane that does not contain the ...
make sure you don't have any conditions blocking this line from being executed
Do you have the gizmos enabled?
took a look at it and everything seems to be enabled yeah
ah you have to actually click the word gizmos wtf
that is extremely unclear
Yeah, it's a bit weird
Adding onto this, if you are using Burst using Unity.Mathmatics. It is more optimized than System.Math iirc.
I know burst is fast, but what’s the downside 🤔
Debug.DrawRay(transform.position, Vector2.left * 100, Color.red);
Is transform.position supposed to be the bottom center of my object? Or did I set it up wrong?
For Unity.Mathematics or burst un general?
Both i guess
if you set your sprite's pivot point to the bottom center, then that is where it's transform.position will be, yes
It only works for certain code
Oh, interesting
The downside of Unity.Mathematics is that you have to write everything in camel case lol.
The downside of burst is it compiles things differently than how Unity normally does it.
I’ve never even heard of Unity.Mathematics, is it new?
It is part of the DOTS package
I think Mathematics is like 4 or more years old now? At least that is when I first started noticing it iirc.
My sense of time is garbage
Ah ok, then maybe it’s because i’ve never looked into DOTS
No it isn’t part of DOTS
It is separate package
I'm sorry, I meant that it is linked to it. A lot of DOTS relies on it
It's part of the stack
DOTS is composed from a number of distinct packages
Note that DOTS is not a single package
Data oriented tech stack(dots)
Ok, I thought so, thank you
I shouldn't have said DOTS package above. That was unclear.
I meant the DOTS ecosystem I guess
Ah. Misunderstood you sorry.
The downside is that you need to write/structure your code in specific way to get any benefit from it. Ideally use the dots workflow for maximum benefit. Also it's a bit harder to debug burst compiled code.
Just enabling burst doesn't mean you're gonna get any benefit at all from it.
Okok
I just mean’t if you are already using burst. Though I forget if Unity.Mathematics depends on it or just benefits from it.
Alright, not sure what else is wrong now 😒
I added the layer to my Character and double checked the spelling
Vector2 direction = (targetPosition - startPosition).normalized;
int layerMask = LayerMask.GetMask("Characters");
RaycastHit2D hit = Physics2D.Raycast(transform.position, direction, 15, layerMask);
Debug.DrawRay(startPosition, direction * 15, Color.red);
if (hit.collider != null)
{
Debug.Log(hit.rigidbody.gameObject.name);
}```
Not getting anything in my console, so it's not hitting
ugh nvm ...
my RigidBody is not on Character but on it's child, works now, thx for all the help
Anyone wanna be friends?
Nice! I assume you're suggesting the value needs to be a 0-1. The docs just say The lower left corner is (0, 0). If the pixel coordinate is outside the texture's dimensions.... The "texture dimensions" threw me off. a U V coord is indeed 0-1 though. Looks to be working now. Thank you.
I'm experiencing the oddest thing. Input.GetKeyDown() is not working when I hold consecutive keys down.
For example, Holding Q and W will log Q and W but then I can't log Tab or E but I can press R or any other keys at least 1 space away.
Has anyone experienced this issue?
Edit, my google finally loaded and this is probably a limitation of my keyboard and not Unity.
Meh, as long as I know it's a hardware issue and not a Unity issue.
Still annoying that the issue exists but it's nice to know that there's nothing I can do about it.
No, this happens randomly and if 24 specific keys cannot be simultaneously pressed then there is nothing that can be done.
To be fair, dont think that was specifically the issue in their case. Sounded more like a hardware issue. Im not sure what the video snippet was supposed to be in relation to 24 because I saw the part where it said 6 max
If its specifically an issue of not being able to press QWE that's a keyboard issue
Bawsi is correct. It is a very specific and niche use case for the project I am working on.
Guys im gonna explode, i watched so many tutorails, read so many docs, I did everything, but i just cant make a third person camera
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
What are you actually struggling with? Breaking down your problem into smaller steps usually helps, if its syntax, then refreshing on C# is a good start, I like w3schools C# course for that - the Unity Learn tutorials will teach you how to use the engine and if you follow along with their projects you can have some small examples to play around with too, but when learning anything, its important to understand why it felt "useless" to you, did you actually follow what the videos did and not get the same result and assume its "useless"? Often it could be that you missed a step
Well, maybe stop for a moment and analyze what the problem is. Maybe you're learning the wrong things. Or giving up half the way and start over just to hit the same walls.
sry it might be a dumb question but i started a VR project long time ago and can't figure out where are the speed movement variable. can someone help me with that?
You have sent the empty code
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
So, what is not working?
I've found it but it doesn't actually speed up the movement for some reason... what could be the reasons behind this?
theres an error in the code and i canr find out look
It tells you the namespace does not exist
i dont think theres anything wrong with the line 2
so im still not sure what to do
What do you mean? The namespace does not exist
can anyone tell me just what is wrong with this teleporter it was working just fine when i was play testing it after writing the code now its acting so weird
why am i being TPed like a few tiles down
the code i think worked fine before
player.transform.position = linkedTeleporter.transform.position;
https://hatebin.com/lmmhtlgyuw MY MAin menu works when i first load up the game but doesnt work when the player returns to it after dying? the play or quit button just doesnt do anything
if I'm using IBeginDragHandler, IDragHandler, IEndDragHandler to handle dragging, is there a way I can invoke a simulated mouse release? I want to be able to drag an object with left mouse, but if another mouse button is used while dragging it cancels the drag.
eventData.dragging = false; works at canceling the drag, but because it's still registering the original mouse input as being held down it just continues the dragging after the mouse is moved anyways.
What does this code have to do with yhat issue?
Not sure, does it automatically cancel the drag, or do you want it to happen?
I just learned something new today...
Awake() and Start() methods are not called on scripts that are not attached to GameObjects in the scene...
I knew I could have classes that didn't required being attached to a GameObjects and still be accessed... but I didn't realize that meant Awake/Start would not be called on the program start, i guess it makes sense they are not truly initiated, even though their methods are there to be accessed.
I was going mad trying to figure out why it could not find my references....
So the options seem to have them attached to a dummy object the scene. or access my references at runtime when the method is called... that seems inefficient. Seems like the beter option is to have them on a dummy object.. unless I'm missing something.
@arctic rock What is your use case -- Awake/Start are called on MonoBehaviours and to a lesser used extent Scriptable objects. Those require instances that are attached to gameobjects. Do you just ahve a normal class?
its in the code thats the prob
You need to read the documentation and understand when and why Awake, Start, and other methods are called on MonoBehaviours
Firstly, if your class is derived from MonoBehaviour, there is a need for neither Awake nor Start to be called, when the script is not attached to the object at the scene.
If you're talking about the normal C# classes, the "Awake" functionality can be implemented in the class' constructors.
Secondly, I don't get your last paragraph. Could you, please, explain the issue in a better way?
Not this code
The problem code is the one with pause and resume
YOu need to access the event Input system, and manually end the drag. The system is quite easy to modify and work with though
oh ok
Creating a state machine, have individual classes as States that inherit from an Interface. I can access all the methods of the interface. but through testing the awake and start are not being called.
Is adding them to an empty object the way to go?
this is the code is there anythng wrong with it? https://hatebin.com/cdswgnhdsu
To interface with Unity in your normal c# classes, you have a few options. Have a Monobehaviour that holds and manages all the c# classes, and call the correct methods at the correct times.
or you can change all your states to mono behaviours
? Where do you pause the game.
Neither script so far has any code that does that
It does not seem like your States require the MonoBehaviour's methods like Start and Awake
I have previously mentioned implementing the required functionality in the normal class' constructors
in my game when you get killed by the monster you just go back to the main menu
and then it doesnt work
Oh, I just reread the original message, I thought you said pausing doesn't work. Sorry
So what do you mean by "doesn't work" explicitly. With as much detail as possible please
the main menu works at first when the game starts but later on after the player dies from the monster. it goes to the main meny and then it just doesnt do anything when i press it, it doesnt even change color when i hover over it
Ok, so buttons stop working.
Did you accidentally have the eventsystem in DDOL or something?
What does DDOL mean agains orry
no
When you hover over a button, look at the inspector for event system near the bottom. It will show data about events like button hover and click
are your button methods on a singleton script
Can you answer steve?
tf u on about
Please don't speak to me like that.
And look up ONE message above your last one
The one from the user named Steve.... which was an apt question for you...
sorry abt that
yes they are
well there is your problem, when you reload the menu scene the methods are still pointing at the unloaded menu scene
Ive researched it quite a bit and it would appear this is the way everyone handles toggling between different panels in a main/pause menu? Is there a better way to do this or a way to refactor it? It just kinda seems bloated to me personally but if this is the standard then I guess its not so bad. (Not my script, got the snippet from a unity forum)
public void ShowItem()
{
itemPanel.SetActive(true);
itemHousePanel.SetActive(false);
itemPetPanel.SetActive(false);
itemPlayerPanel.SetActive(false);
currentQuestsPanel.SetActive(false);
allQuestsPanel.SetActive(false);
Q001PickFlowerSwordButton.SetActive(false);
Q002KillTheSpidersButton.SetActive(false);
Q003CatchHurtButterflyButton.SetActive(false);
Q001InfoPanel.SetActive(false);
Q002InfoPanel.SetActive(false);
Q003InfoPanel.SetActive(false);
statPanel.SetActive(false);
}
I generally use lists and loops if I need to do something similar
I was afraid that would be the case, ive done a few for loops but I dont fully understand them yet, never done anything with lists.
absolutely not the standard
well, maybe a beginner mistake, I started out doing that and then upon researching to refactor it, everything I found was like that, videos, forums. Seems quite a few people do that
As a very overly broad statement, I feel that if I have written code which requires large numbers of very specific references, it's has the smell of poor architecture...
I feel like things should become generic enough, and organized with their own controllers in such a fashion that you don't often need to handle a bunch of different things in very direct and specific ways.
But handling each thing individually as in that screenshot makes sense early on or for prototyping and playing around. Lists and loops would be a reasonable next step
Let the default state be off, and any time you need one, keep track of it, turn it on as needed, when your done with it, or need to switch, turn the active one off, and the new one on
https://www.w3schools.com/cs/index.php
Might wanna go through this. Loops are probably something you should understand before touching unity
They are a foundational thing that any basics course would teach early on
Ill mess around with that as im a little more familiar with doing something like that. Thank you.
Thank you for the link, I have never heard of that website and after a quick glance, it should definitely help me figure out for loops.
do you know why I can't reference my script "FPSController" in my inspector?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
public FPSController fpsController;
void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.tag == "Player")
{
fpsController.Hit();
Debug.LogWarning(collision.transform.root.name);
}
Destroy(gameObject);
}
}
Show MainCharacters inspector
When that happens to me it's usually a compiler error or when i forgot to save a .cs file
unity doens't do a great job of complaining that there's a compiler error. It just uses the last good version
(in the editor at least)
can't reference scene objects from a prefab asset
oh ok !
but for exemple if I had multiple MainCharacter in my scene, how my script would know wich one pick ?
Lots of ways. Perhaps a singleton?
I can cancel the drag, but the system still registers the mouse as having been pressed down so is ready to queue up another drag immediately as soon as the mouse starts moving again. I need it to think the mouse has been let go entirely
Is there some documentation to point me in the right direction? Thanks
Hi, I'm trying to make an inventory system and I'm having some problems not entirely related to the code, let's say I feel like the code doesn't really utilise the power of object orientation. Let's say I have different kinds of items and for each type I want a slightly different system... For example weapons are not stackable, and can have duplicates, materials are stackable and cannot have duplicates... and the UI for the slots is slightly different from type to type. Does anyone have some tips?
I have another script to generate a falloff-map. Is there a way to apply the falloff map to the entire terrain without iterating?
You can have all of the terrain managed by one monobehaviour.
So you don’t have to get components.
You can also have each modifier subscribe to a delegate.
Hello I am new and would like to create a VR app with hands that are detect through the camera for a project. Can you tell me how I could do and/or the steps to follow.Thanks who can't help me !
first thing, in this server do not cross post
oh sorry I'm new
yes, I can read. your question belongs in #🥽┃virtual-reality next time look for the correct channel
ok srry
Can i make a OnTriggerEnter2D function with a collider that is not attached on the gameobject in wich the script is ?
no, OnTriggerEnter2D will only be called on the object the has the collider (or its rigidbody parent if it has one)
explain the purpose of what you are doing and perhaps a better solution can be suggested
but you know how i can't do it ?
I have a boss that jumps which has a rigidbody and a collider that prevents the object to fall and i need another collider to damage the player .
i don t want to make another script just for that
why do you need another collider for that? can you not just use a physics query?
Thanks, Will try this out. But I still dont know how to apply the entire Falloffmap on the terrain.
Hi
Hello, I was wondering if there was a builtin way in Unity to efficiently get the nearest (or approximate nearest) neighbor?
Neighbor?
Can you be more specific?
Like I would like to get the object of certain type that is the nearest of a certain position
I did implemented a spacial hashing grid but I would like to know if there is a builtin way to do that
You can have another class store all the GameObjects in a list and iterate through that.
Hashing grid seems like the best way though.
Hi guys, im looking for a Domino Board Game tutorial, or something like, have someone did it ou saw something about how to do a domino board game in unity? seems so hard to do
Ok thanks so im gonna stay with that method
There's no built in way. You could do a search with OverlapSphere calls - starting with a small sphere and getting larger progressively.
Is it efficient performance wise? Like can it filter and only hit with objects of a certain type?
you can filter it by layer
"efficient" is something that can only be compared to other methods - and the comparison will depend on a lot of factors
such as how many such objects there are in the scene
Ok I see so its iterating through all objects even those that are very far from the sphere?
no
The method of storing all the objects in a list is doing that
I'm saying you'd compare this method with that one
and because that one will be fast if there are few objects, and slow if there are many objects, the comparison depends on the object count
it may also depend on other factors - such as how densely populated they are in the scene
Oh ok got it
etc
OverlapSphere requires physics though
Im gonna do some testing, thanks for the suggestions!
yes they do
If they already have physics then sure.
I wouldn’t advise it otherwise but if they do it is fine.
I mean basically the nice thing about physics is the queries use spatial data acceleration structures
If you didn't have physics already then by far the most efficient algorithm to use would be to store your objects in similar spatial data acceleration structures
we're just taking advantage of the already existing one.
are those sort of quad tree ?
quadtree is such a structure yes.
In 3D it's called OctTree though
but there are others. Not sure what PhysX uses, but something like that
Ok thanks so its probably way more efficient than my current system 😅
probably. The main limitation is just that Unity doesn't directly expose those structures so you're stuck with less than ideal queries like OverlapSphere which don't really answer your question directly.
In general though OverlapSphere is a great starting point to get a small list of obejcts which you can then just linearly scan to do the normal "closest distance" algorithm
A Bounding Volume Hierarchy
I guess this is more of an opinion question than anything: How do you handle instances for UI screen? Instantiating each screen as required from and destroying on exit, or pool everything at application start (or scene enter as appropriate) and activate/deactivate as needed?
I spawn all the screens for the particular menu and enable and disable them as needed. Though it largely depends on the complexity of you UI and often you switch them.
I think it depends on the life cycle of the UI your spawning and how generic your elements are - if they are reusable, then a pool makes sense, if they are only ever shown in very specific conditions then spawning and destroying seems fine, if they are toggled often like a inventory then spawning it when the scene loads and destroying it when the scene unloads sounds fine, unless some need to persist across scenes, then spawning it once and keeping it in memory may be a better option, as Mike suggested though, it depends on the complexity of your UI and the lifecycle of what is actually being created to begin with, also if the concern with performance or with design preference as well
If you are using the same elements but will different values, like a (character menu for example), you can use the same prefab but use a script to set the values of the elements.
its generally a very good idea to reuse existing ui instances as much as possible and minimize layout updates. UI refreshes produce garbage allocations like a MF
this is not really a question for populating things (I run a MVP architecture with interactor and repository, so all my data lives somewhere completely removed from the UI). But really only for creating new gui objects, potentially en masse (for complex screens) on demand or on load
well, creating ui layouts procedurally from scratch without pooling is expensive but, depending on the design, unnoticed or forgiven by the user
the GC I didn't really saw as an issue so far, but the intial layouting is a noticeable CPU hog (when spawning bigger elements unity slaps me with very noticeable framedrops which are noticeably ugly)
I am not doing procedual layouts. The layout is set up in the prefab and is not changed dynamically. Where dynamic changes happen they're isolated to subcanvases to contain the setdirty propagation while also doing the layout calculations manually (avoiding layoutgroups)
a prefab is a blueprint for a procedural instantiation
its not really an issue that only affects UI, you should basically pre-allocate, pool or reuse everything in a game
instantiate/destroy are not your friends 😉
but ofc, you also need to stay productive and there are other concerns like workflow, so ymmv
in which case, what profiler marker does unity utilize to show the layout process? I know there is the canvas layout marker, however what tends to bog frames seems specifically the instantiate call
when you deep-profile you will find a lot of time and memory is spent in relayout and text refreshes
unless unity calls it's layout engine twice, once during instantiation and a second time during it's "normal" layout
layout should only run once per frame in which changes have happened, unless you manually call it more often
I am aggressively pooling everything bar UI already, so this is not news to me
Would it be a good idea to make a lot of my integral scripts into scriptableObjects (rather than attaching to a blank gameObject in every scene)
For instance one script contains a movement check that is used constantly in combat
Depends.
If you need to reference the same instance cross scene and do NOT plan on using addressables/assetbundles, that move can make things a lot easier
If you want to push design work from code into editor, the same goes
If it's just dumb data where some component depends on some instance of values being around, you can also add a [RequireComponent()] attribute to the class that needs said instance
Alright
So probably just keep it to player/enemy lists and inventories
It doesnt really make sense to use an SO here. The movement check is pretty much just gonna be a method, and you likely arent gonna have multiple instances of this SO
SO is really just a data container, the main use case is just reading data from it. Like data about an enemy, how much health, speed, damage it has. This moves the work from defining it in code to being able to define it in editor
Alright
to add to that, it's a datacontainer that lives outside the scene. So in case you have a lot of entities relying on the same data (say maxhealth or some other set of configurations) it's also a good use, as you only get one instance (or as many as you have assetbundles loaded) instead of one per entity, potentially saving you a lot of memory overhead
Yeah although I do have current battle stats applied directly to the playerStats SO because party switching would make that annoying to keep track of otherwise
Well regardless you would be reading off the data and copying it to your instance, so its not like you're really saving anything memory wise in this case. Especially required if values can be changed (which would be a majority of cases)
uhhh..... why would you copy something like maxhealth and config data in general?
class MyAwesomeHero{
public MyAwesomeSettingsSO Settings;
public int MaxHealth => Settings.Maxhealth;
}
``` no copying in sight
in addition to skipping the needs to sync for changes in the design data
Especially required if values can be changed
so all you need to worry about is runtime data living in your objects
I honestly do not get what you mean by this
If for example a buff gave you more max health, suddenly you cant just read off the SO data. I am saying if the data can be changed, you're gonna have to store it anyways
to adjust the example from before
class MyAwesomeHero{
public MyAwesomeSettingsSO Settings;
public int MaxHealth => Settings.Maxhealth;
private int CurrentHealth;
private void Start()
{
CurrentHealth = MaxHealth;
}
}
there is only one int as member of class MyAwesomeHero
... you have to store some of the data (the mutable part) per entity. nothing stops you from sharing the inmutable part
Yeah right now I just have two sets of data for each unit (base and current)
otherwise you'd have both maxhealth as well as currenthealth on the character and would need to reintroduce the second value case you get some heal effect (health being adjusted both directions)
And have the game calculate it every state change (status start/end, equipment change, etc)
Heal would just be something like health + healvalue
I usually just treat SO as a container to read off once then forget it exists. Worrying about the memory here is really a micro optimization imo
it's also a good habit to have as it doesn't cost you anything while helping with memory
Which is why I called it a micro optimization. Even if this was done for 1000 instances it would have 0 visible affect. And I find it easier to define a plain c# class with all the values I want, then put that inside the SO instead of listing every field. Then whatever uses the data just copy the whole thing. I'm on mobile or I'd try to show more of an example
That's why I called it a good habit. If everything is generally a bit slower than it could be by using a slightly better solution that doesn't cost you, you win in the long run (alongside avoiding doing unnessary work, the fastest code is code that doesn't run after all)
I run most of my systems datadriven reading in shit from .csv files in plain c#, but also see to keep what I can shared, deploying what amounts to prototype and flyweight pattern
Would I use one if I need to copy some values over a scene (for example, initiating enemy positions in a fight by taking a number of IDs and spawn locations determined by whatever is causing the fight and putting them through an SO for the script in the combat scene to use)
Sounds like you simply need to execute some code, anywhere - provided character information, set position of characters etc.
Yeah Im trying to have a script that allows other scripts to pass data about what enemies are in a fight and where to spawn them (for the initiator script in the combat scene to use)
it sounds like you would be setting the data at runtime, in which case I wouldnt use an SO. You could just do this from an object that exists in DDOL
Copying data between scenes implies that you're needing persistent data (a save/load system or ddol) and not necessarily an SO (immutable in most practical cases)
hi chat, help me pls
should this line work?
script1 = transform.parent.gameObject.GetComponentInChildren<Script1>();
i wrote this in Start method, all objects exist, all scripts were attached but it doesn't find needed script
how did you check?
if its not finding it then its not there. simple as that
or you're looking on the wrong obect
anyway should just make a field and link this in the inspector
I always find it questionable to use .parent or like search through children at runtime. Seems very fragile
yea same
if its on the same object i rather keep the reference in the script as a field
then make a public getter if i need it else where
Unity throws errors about empty reference
thats very vague
i can't, this is a line from enemy's script so bc there won't be one enemy i should use this instead
would it work if everything were set correctly?
it could but its very fragile
wdym?
you should just link the component you want through inspector
i will to copy the object, will it automatically assign the script?
nothing happens automatically, thats what scripts are for . You tell it something specific to do
i mean, if i assign the parent's script through inspector, will it assign the copied parent's script to the child?
@rigid island
it will reference whatever component you dragged inside, if its on the parent then its the one on the parent
nothing gets "copied"
references are linking to the specific component , you can drag it into any other script , it just all leads to the same one
Dont know where you got the idea that you cant. It works and you should directly assign the reference
ok i have a structure like tgis:
-Parent
--first child obj (has Script1)
--second child obj (has reference that Script1 was assigned to through inspector)
will copied object also have copy of Script1 assigned to reference?
how are you "copying" the object? like spawning a prefab, or something?
yes and then use ctrl + d
so I'm doing a multiscene project and the audio plays when expected on the first run using this code...
{
// Call your method to reset triggers here
Run();
}
// Start is called before the first frame update
void Run()
{
instance = this;
PlayerPrefs.SetInt("Level", level);
scoreText.text = "Score: 0";
multiText.text = "Multiplier: x1";
phase = Phase.OPEN;
dialogueBox.SetActive(true);
if(healthFill != null){
healthFill.color = Color.Lerp(Color.red, Color.green, healthBar.value / healthBar.maxValue);
}
dialogue.InitDialogue(phase);
}```
the last click of the dialogue (init dialogue) involves running this function:
public void TerminalButtonPress(){
if(phase == Phase.OPEN){
theMusic.Stop(); //this didnt matter before, but it totally does during resets w pause button
theMusic.time = 0;
theMusic.Play();
playing = true;
noteScroller.started = true;
}
else if(phase == Phase.CLOSE){
levelSummary.SetActive(true);
}
}```
on the first run, this works as expected. on the second, for instance, if i pause, return to home menu, and then enter the scene again, well, first of all, audio doesn't play on awake when i enter ANY scene for the second time. which is Very Unsettling. second, when i run this code a second time, the music does NOT play. if i debug in that function, it claims it's playing, but by update, it is not playing for some reason. no code touches turning off the audio.
ctrl+d? wait, are you spawning this at runtime? if so, it should be able to access the script, yes (assuming it is the same object, as in, you are spawning a prefab or something similar)
but it seems like you might be assigning a script to one child, then creating a new object which is also the parent of the same child-- in that case, no, that wouldn't work. it needs to directly have the script attached
#💻┃unity-talk message
#📖┃code-of-conduct
and stop crossposting
oh, ok i'm confused
nevermind, i will try it and see, but anyway thanks
Let me know if that works.
I can show a video if desired. I feel like I have to be missing something about the audio player in general, but this has never happened to me before...
you said this happens when you pause and go back to the main menu. are you perhaps setting the time scale to 0 when you pause? and just not setting it back to 1 when you return to the menu?
Oh fuck. Let me check that 😭😭😭😭
Oof, gave it a try and no luck-- I set it back to 1 and checked it stayed 1, bug remains the same
is there a way to make child classes inherit an editor function called on a parent class
I am trying to edit a mesh at run time like this:
foreach (var v in vertices )
{
if (Vector3.Distance(v, contactPoint) <= damageRadius)
{
continue;
} else newVertices.Add(v);
}
var uv = new Vector2[newVertices.Count];
mesh.uv = uv;
mesh.Clear();
mesh.vertices = newVertices.ToArray();
mesh.RecalculateBounds();
mesh.RecalculateTangents();
mesh.RecalculateNormals();
However the mesh just becomes invisible - ultimately I am trying to get a sort of dynamic destruction type thing going on
Any ideas?
What about indices/triangles?
Also, you can double click the new mesh in the mesh filter to inspect the mesh attributes.
Sure. Wether it's editor function or not wouldn't matter in terms of inheritance.
Though, obviously, you need to make sure it is not included in the build.
I would suggest using shaders or procedural shapes to do this
What exactly is a procedural? I vaguely know the term but i am not sure how I would make one
Any good tutorials i should watch?
Basically, something not done by predetermined meshes but rather shapes that are generated by code
Well, that's basically what they're doing. Modifying the mesh in code.🤷♂️
That enters the "procedural generation" category.
Kinda ig.
IIRC modifying meshes can lead to lots of garbage collection, hence why I recommended full procedurals
@drowsy steeple what are you trying to achieve exactly btw?
It's still not clear what you mean by "procedurals" or "full procedurals". I never heard that term being used like that.
a dynamic destruction system that is similar to r6 siege
obviously not on the same level or thoroughness because im not there yet
but something similar
lol
I mean’t meshes that are fully generated, instead of modifying preexisting ones.
Oh. Forget everything I just said that would not suite that lol.
That is out of my area of expertise. Though I do know a asset store package for that if you want it.
Sorry I though you were going for something completely different. 😅
sure, send it
Have not used it myself but it has good reviews.
Im reading my logs over and now its telling me that my mesh has 0 tris or verts originally... could this be something silly like read/write not being applied ?
Yes, that could be it.
The mesh shows that it is read and write but could it be possible that the instance of it in the scene isnt?\
maybe i placed it down before i switched it to read/write
No. Unless it's a different mesh.
Placing an object with the mesh in the scene doesn't create a new copy of the mesh. it references the asset data.
You never said anything about my initial message though.
Or shared any debugging results.
i updated it to attempt to recalculate tris:
Vector3 localContactPoint = transform.InverseTransformPoint(contactPoint);
Debug.Log($"Local Contact Point: {localContactPoint}");
Vector3[] vertices = mesh.vertices;
int[] triangles = mesh.triangles;
Vector2[] uvs = mesh.uv;
Debug.Log($"Original Vertices Count: {vertices.Length}");
Debug.Log($"Original Triangles Count: {triangles.Length / 3}");
List<Vector3> newVertices = new List<Vector3>();
List<Vector2> newUVs = new List<Vector2>();
List<int> newTriangles = new List<int>();
Dictionary<int, int> vertexMap = new Dictionary<int, int>();
// Visual debugging: Draw damage radius
Debug.DrawRay(contactPoint, Vector3.up * damageRadius, Color.red, 2f);
// Keep track of vertices within the damage radius
for (int i = 0; i < vertices.Length; i++)
{
if (Vector3.Distance(vertices[i], localContactPoint) > damageRadius)
{
vertexMap[i] = newVertices.Count;
newVertices.Add(vertices[i]);
newUVs.Add(uvs[i]);
// Visual debugging: Draw kept vertices
Debug.DrawRay(transform.TransformPoint(vertices[i]), Vector3.up * 0.1f, Color.green, 2f);
}
else
{
// Visual debugging: Draw removed vertices
Debug.DrawRay(transform.TransformPoint(vertices[i]), Vector3.up * 0.1f, Color.red, 2f);
}
}
// Log new vertex count
Debug.Log($"New Vertices Count: {newVertices.Count}");
// Update triangles to use the new vertex indices
for (int i = 0; i < triangles.Length; i += 3)
{
int v0 = triangles[i];
int v1 = triangles[i + 1];
int v2 = triangles[i + 2];
if (vertexMap.ContainsKey(v0) && vertexMap.ContainsKey(v1) && vertexMap.ContainsKey(v2))
{
newTriangles.Add(vertexMap[v0]);
newTriangles.Add(vertexMap[v1]);
newTriangles.Add(vertexMap[v2]);
}
}
// Log new triangle count
Debug.Log($"New Triangles Count: {newTriangles.Count / 3}");
// Update the mesh
mesh.Clear();
mesh.vertices = newVertices.ToArray();
mesh.uv = newUVs.ToArray();
mesh.triangles = newTriangles.ToArray();
mesh.RecalculateBounds();
mesh.RecalculateTangents();
mesh.RecalculateNormals();```
2024-08-01T02:12:11.948 INFO D.D.CollisionHandler_OnCollisionStartEvent : Original Vertices Count: 0
2024-08-01T02:12:11.948 INFO D.D.CollisionHandler_OnCollisionStartEvent : Original Triangles Count: 0
2024-08-01T02:12:11.948 INFO D.D.CollisionHandler_OnCollisionStartEvent : New Vertices Count: 0
2024-08-01T02:12:11.948 INFO D.D.CollisionHandler_OnCollisionStartEvent : New Triangles Count: 0
2024-08-01T02:12:11.948 INFO D.D.CollisionHandler_OnCollisionStartEvent : Destruction Log 6```
This is what the logs show
granted i did ask chatgpt for help recalculating the tris so that might be source of error
Where does the mesh reference come from?
GetComponent<MeshFilter>().mesh
The monobehaviour is on the same gameObject as the meshfilter
Can you pause just before this code executes, select the object with the script and double click the mesh in the mesh filter? Then take a screenshot
can i subscribe to another GameObject's OnMouseDown?
private void foo() {
Debug.Log("callback worked");
}
private void bar() {
GameObject gObj = Instantiate(gObj, Vector3.zero, Quaternion.identity);
gObj.OnMouseDown.AddListener(foo);
this doesn't actually work because gObj is a GameObject, not the class defined in gObj's script component.
but can i do something similar to this?
OnMouseDown is not an event, it is a callback. So no
You can call a method in another script FROM OnMouseDown, or invoke an event from it
That is the closest you will get
yeah i was also considering invoking an event from OnMouseDown
but i wouldn't have a reference to that event
Make it so you do have
i'm struggling to see how to do that, since i can't pass an event through Instantiate()
you have a GameObject reference. you can just attach a monobehaviour to it that implements IOnMouseDownHandler and publishes an event when that happens, just subscribe in bar() when you fetch it
event can be passed any type inside functions, make init method
why make it so complicated tho?
public class EventSource{
public event Action SomeEvent;
}
/*somewhere else where you want to subscribe*/
...
eventsource.SomeEvent += SomeEventFunction; // eventsource is an instance of EventSource
...
the event keyword is specifically made so you can fiddle with other entries on it but only add or remove yourself
no need for big init function where you pass stuff in or whatever
is this a different solution to the one you mentioned above?
nah, it's the same
EventSource just missing the interface and monobehaviour inheritance
Foo instance = Instantiate(prefab)
instance.init(eventRef)
This seems way less complex to me
i think i understand that better
it also obscures what happens there if all you do is subscribing to an event
No it does not
init does not tell me what happens there, I have to look at the implementation
init just tells me it inits something
So look at the implementation... but you can just make a summary....
Still far less complex and more foolproof
but why should I if I can, you know, use a specific language feature of c# and not jump needlessly through the codebase?
Because it is easier and more straightforward?
it's not. that is my point
It's not in your opinion
I disagree. I gave up on the way you recommend quite a while ago because it just doesn't cut it most of the time
¯_(ツ)_/¯
Why would you need to know what happens there? It's up to the object implementation. You just need to know that it's required to initialize the object properly.
so i need to attach eventsource to the GameObject i instantiated?
the orginal question was: how do I subscribe to an event
I replied: event += eventhandler
somehow that is too complicated
excuse me for being confused
I think the issue is that they don't just want to subscribe to an event. There's more context to the issue that was not clarified correctly to us
I was responding to your response about init being to complicated. Which ..... how?
It is obviously not
sorry for delay, in a warzone game
This seems fine. Okay. Can you debug the name of the mesh that you're accessing in code?
Or just use the debugger and step through the code
because c# provides you with a language feature specifically desgined to subscribe to events? so if you want to subscribe to an event you do just that? instead of obscuring intent?
You can subscribe to the event in init..... that was the suggestion
It is the exact same, just in a different place with one less class
not directly related to your problem but Instantiate can return the actual component you want, you just drag in the component you want to instantiate it from and itll spawn the whole prefab along with it.
so you'll have direct access to the script
rather than going through GameObject
how do you ... drag something into code?
in inspector
prints out "Cube instance"
anyhow, given how deeply this is steeped in opinion and people deciding to bring up perceived past slights, I'll take my leave
glhf
i'm kind of getting lost in all the different options
i'm not sure which option to follow
Hmm... And if you print mesh.Vertices.Length right after that or in the same message.
I am not sure why you are so upset? There was no fighting, and no slights that I saw.
Please don't make this into something it is not
Sorry if my difference of opinion hurt your feelings 🤷♂️
People do things differently. I never said your way is wrong, I said I prefer my way.
maybe i'll just try init because i seem to understand it best at this point
my suggestion was simply how to get the script you want when instantiating it. wasnt a separate option on how to do this. The options you have are basically either use an event from OnMouseDown or directly call the method you want from OnMouseDown
either one works, i tend to directly call methods if I can.
i thought the init method was also using an event
The difference of opinion was only about how to subscribe to the event
It is
yeah
You could also skip the event and just call the end method directly instead of init or subscribing
mmm that might have more complications because of the context
because the children objects don't know which child they are
so i'd have to tell them somehow
thats completely a new problem from what youve initially described of just not being able to "subscribe" to a unity message
This is some of the missing context that dlich was talking about
oh... i can give context but i need to think about how to explain it
Show your code and describe what you want to do.
This is what we call an XY problem. You asked how to do X, which is your solution, but we want to know Y which is the problem you want to solve
Think first => give context => ask question.
Not the other way around
yes by all means there may be a better approach than what i've asked about
okay i can also send code
says 13564
Ok, so it does have vertices at that point. What about your other messages after that?
On the collision it shows that it has 0
Also, can you send the updated code?
private MeshCollider collider;
private MeshFilter meshFilter;
private Mesh mesh;
public void Awake()
{
Debug.Log("Destruction Log 1");
collider = GetComponentInChildren<MeshCollider>();
meshFilter = GetComponent<MeshFilter>();
mesh = meshFilter.mesh;
// item = GetComponent<Item>();
// item.mainCollisionHandler.OnCollisionStartEvent += CollisionHandler_OnCollisionStartEvent;
Debug.Log(mesh.name);
Debug.Log(mesh.vertices.Length);
Debug.Log("Destruction Log 2");
}
void OnCollisionEnter(Collision collision)
{
float damageRadius = 1.5f;
Vector3 contactPoint = collision.contacts[0].point;
Vector3 localContactPoint = transform.InverseTransformPoint(contactPoint);
Debug.Log($"Local Contact Point: {localContactPoint}");
Vector3[] vertices = mesh.vertices;
int[] triangles = mesh.triangles;
Vector2[] uvs = mesh.uv;
Debug.Log($"Original Vertices Count: {vertices.Length}");
Debug.Log($"Original Triangles Count: {triangles.Length / 3}");
if (vertices.Length == 0 || triangles.Length == 0)
{
Debug.LogError("Mesh has no vertices or triangles!");
return;
}
List<Vector3> newVertices = new List<Vector3>();
List<Vector2> newUVs = new List<Vector2>();
List<int> newTriangles = new List<int>();
Dictionary<int, int> vertexMap = new Dictionary<int, int>();
// Visual debugging: Draw damage radius
Debug.DrawRay(contactPoint, Vector3.up * damageRadius, Color.red, 2f);
// Keep track of vertices within the damage radius
for (int i = 0; i < vertices.Length; i++)
{
if (Vector3.Distance(vertices[i], localContactPoint) > damageRadius)
{
vertexMap[i] = newVertices.Count;
newVertices.Add(vertices[i]);
newUVs.Add(uvs[i]);
// Visual debugging: Draw kept vertices
Debug.DrawRay(transform.TransformPoint(vertices[i]), Vector3.up * 0.1f, Color.green, 2f);
}
else
{
// Visual debugging: Draw removed vertices
Debug.DrawRay(transform.TransformPoint(vertices[i]), Vector3.up * 0.1f, Color.red, 2f);
}
}
// Log new vertex count
Debug.Log($"New Vertices Count: {newVertices.Count}");
// Update triangles to use the new vertex indices
for (int i = 0; i < triangles.Length; i += 3)
{
int v0 = triangles[i];
int v1 = triangles[i + 1];
int v2 = triangles[i + 2];
if (vertexMap.ContainsKey(v0) && vertexMap.ContainsKey(v1) && vertexMap.ContainsKey(v2))
{
newTriangles.Add(vertexMap[v0]);
newTriangles.Add(vertexMap[v1]);
newTriangles.Add(vertexMap[v2]);
}
}
// Log new triangle count
Debug.Log($"New Triangles Count: {newTriangles.Count / 3}");
// Update the mesh
mesh.Clear();
mesh.vertices = newVertices.ToArray();
mesh.uv = newUVs.ToArray();
mesh.triangles = newTriangles.ToArray();
mesh.RecalculateBounds();
mesh.RecalculateTangents();
mesh.RecalculateNormals();
Huh. Where does it show 13564 then..?
Use paste sites please
This is way too much code to put in directly.
3-5 lines is ok for formatting usually
Debug the name of the mesh on the collision as well.
basically i have a GameObject that's sort of like a machine with different controls on it, and displays. The controls and the displays are child GameObjects created by the parent's Start() function. when the controls are clicked on, the machine needs to display the right output. this is the code on the parent object
says cube instance... but now it is properly showing the original tris and verts counts
still shows the new as being 0
it's meant to be a puzzle for a puzzle game
I wonder if you're mixing up logs...🤔
Oh i see now, the 0's are coming from collisions that happen after the initial 
As for the new vertices, you don't add all the existing vertices to it.
isnt that done here?
if (Vector3.Distance(vertices[i], localContactPoint) > damageRadius)
{
vertexMap[i] = newVertices.Count;
newVertices.Add(vertices[i]);
newUVs.Add(uvs[i]);
// Visual debugging: Draw kept vertices
Debug.DrawRay(transform.TransformPoint(vertices[i]), Vector3.up * 0.1f, Color.green, 2f);
}```
how do i declare the init function?
Pass the event holder as a parameter and just subscribe to it
Oh. That is completely irrelevant
it goes in the script right?
Name it RaInBoW() for all it matters
In the scrupt you want to respond to the event, yes
wait how does this solve my problem...
OnMouseDown() {
MyEvent.Invoke()
}
When it invokes, you know MouseDown was called
but we're talking about two different scripts here, right?
No.
Why would it go in the one with MouseDown?
because mouse down needs to invoke the event...
Yes, which is EXACTLY why Init would not go in it
okay
You CALL init from the mouseDown script
But it is defined and implemented in the other
how does it get a reference to init?
You have to get the reference to the script at some point
how?
That is needed no matter which method you use of course
I don't know your architecture. But getting references is something you should absolutely know how to do.
See this guide
https://unity.huh.how/references
oh oh this is good
yeah this is really good
thanks
i probably want a serialized reference or DI
Serialized reference should always be the #1 choice.
And DI is what the init method I was talking about is.
You are directly injecting the needed reference in so it can subscribe itself
the serialized reference section talks about the inspector
i don't think i can do that, since i'm instantiating the GameObjects in code
right?
Correct
See the example. Instantiating object should pass references.
Instantiate returns a reference, like I showed in the example code
This one specifically https://unity.huh.how/references/simple-dependency-injection
Serialized reference Aethenosity mentioned will be in that case in the instatiating object
Or in another manager that will initialize it in turn
so which code goes in the instantiated object's script?
You only add some vertices and only if the condition is true.
Assets/Permutor/ManagePermutor.cs(68,20): error CS1061: 'GameObject' does not contain a definition for 'Init' and no accessible extension method 'Init' accepting a first argument of type 'GameObject' could be found (are you missing a using directive or an assembly reference?)
you need to be using the correct type for your variables rather than just GameObject
Init is a method YOU make in a script
that changes nothing about what i said or what you need to do
what's the type?
how should i know? its your code
MyScript prefab
MyScript instance = Instantiate(prefab)
instance.NameOfMethod()
Are you asking what a type is?
classes are types
no no i know what types are
then you should know what to change it to
Well then you should know that we cannot answer that question
oh you're instantiating a script?
no, you are instantiating a prefab. but you can refer to it using any of the components on the root of the prefab
just like literally any other object you can (and should be) reference the components directly
You're instantiating a prefab together with whatever is attached to it(including your script)
You instantiate an Object a copy of whatever you pass in the field
No
i thought you knew what types are
It is the class, as navarone said
And NameOfMyScript, Camera, Rigidbody, GameObject, String, Foo, MyStructName
a script with the filename foo has type foo?
those are some of the built in types, yes. if that is all you know about types, then perhaps start with the beginner courses pinned in #💻┃code-beginner
Not filename
Filename is irrelevant
no, a script with any filename that has a type definition for type foo has type foo
oh it's the name of the class defined in the script?
classes are types. so yes.
GameObjects are types
but ok let me try the name of the class
Script is a near meaningless word that just means file. It confuses many people
gameobject is just a glue that holds all the components on it
Get in the habit of just calling them classes
but yes this very much a #💻┃code-beginner problem at this point
Note that Instantiate takes an OBJECT not a GameObject.
Those are distinct things
A class is an object
Unity Object, so only MB or alike, in case of instantiate
confusing enough there is the c# Object base class
I wouldn't have minded a UObject baseclass
Do you guys ever make empty monobehaviors to put on gameobjects? like either to identify them or some other reason? if so what reasoning?
GameObject is unity's "container?" object class. Game objects contain a list of a components (a.k.a. scripts). You can reference a game object through one of its components.
sure
GameObject is not the base class
poor wording let me rephrase
maybe i should move to the beginner channel
was this to my question?
yes
for what reasoning?
because I rather use type-safety than tags/strings
ok makes sense yeah
didn't know if it was bad practice or anything I was gonna make one wanted to check in here first though to test the waters
same. I've used empty monobehaviours for when I need multiple tags on a single object (and then sometimes they become event busses)
also TryGetComponent is soo much more convienent than doing
if(other.CompareTag)
var comp = other.GetComponent
if(comp != null) etc.
very true
I call those tag components. They are simply to replace the tag system for me. TryGetComponent(out MyTagComponent _) is pretty nice
Oh.... too slow lol
Isn’t getcomponent a lot slower though?
Or is trygetcomponent just so much faster than get component
it just does the same thing plus a null check
They are basically the same speed if successful
If it fails to find the component, TryGet is much faster.
But also TryGet gives you the component
TryGetComponent is not any faster than GetComponent, it just combines the GetComponent and the null check and also doesn't allocate anything in the editor when the component does not exist on the object unlike GetComponent which allocates an instance to throw MissingComponentExceptions
How about compared to checking tags
Checking tags is gonna be faster
Ah
Tags just.... suck
I agree
i mean, you'd have to profile it. likely CompareTag is faster, but if you need a specific component, it's easier to just TryGetComponent instead of CompareTag and TryGetComponent
Ah okok
you should only really be getting a component on events like on collision. The difference could only really be meaningful if your doing like 1000 at once or running it every frame.
Ah ok got it
wdym by that ? oncollision is not the only time to get a component
Then is it usually a bad sign if getcomponent is running every frame, but i still need the component
i mean, if you are just getting the same component over and over, just cache the reference instead of calling GetComponent every frame
Well i mean if it’s not guaranteed to be the same object’s component
They said "events like"
So I think they mostly meant just not update. Things like spatial queries, collision events, etc
on collision was just an example. You're only getting components when you get a new object that you don't anything about yet.
well then your question was too abstract and unless you provide a specific example then the answer is going to just be 
Ok then
GetComponent is not very slow so there's not much harm in calling it every frame if you need to, but if there is no reason to call it every frame then don't. but the same can be said of literally any operation that doesn't need to happen every frame
imo if you run into that situation it'd probably be best to look into refactoring so that those objects are collected in an easier to query way.
Refactoring?
and yeah get component is just a list iteration (which will usually only be max 10 elements), it's not likely to be a big bottleneck
I got some of my OverlapsNonAllocs inside varying polling timings
some can be even just every 0.01 sec etc.
I see i see
Rewriting the code
Here is some actual data to back up the claim that GetComponent is not slow.
Code used for the tests
1 GetComponent call on an object measured 100 times had a max time of 0.01ms (or 1/1000 of a frame at 100 frames per second)
100 GetComponent calls in a loop on the object maxed out at 0.6ms (or 6/100 of a frame at 100 frames per second)
1000 GetComponent calls maxed out at 3.9ms (or about 39/100 which is only a bit more than 1 third of the frame at 100fps).
It isn't a super comprehensive test, and only tests using GetComponent on an object with 10 components added in a random order as well as getting the same component over and over, but it does at least show that this operation is pretty fast and doesn't really need to be worried about too much.
Of course, like any operation, if you can avoid repeating it, then do so.
Is there a way to loop through every GameObject in a scene via a script, without inheriting from MonoBehavior/something close?
Everything I can find on the wiki shows me the typical way of just using GetComponents<T> but, not how without a component active
before I provide an answer to that, I gotta ask why you would want to do that
The GameObject I need is active in the scene somewhere, but I can't access it looking in the hierarchy, I have to get at its Skinned Mesh Renderer
It's an incredibly specific case but.. Hopefully a pretty general concept
it's going to be incredibly fucking slow compared to getting the reference to that object properly, but you can get all of the root gameobjects of a scene and foreach over their transforms (and their child transforms recursively all the way down).
Provide more details about your actual use case and a proper solution can be suggested
Even without knowing the context, I'd claim that this isnt an incredibly specific case. You've just chosen to do something backwards
Trust me lol, it's not a choice 🫠
If I could add a component to the gameobject and be done with it, I would
until you actually give any actual details there's no point in arguing your case about why this is necessary. everyone is going to (rightfully) assume it isn't necessary
thanks for sharing, I always find these interesting
Somewhere in the scene, Dalg_Chestplate_Armour is added, and then applied to the player as armour like this, I need to get at it and edit the emission values of the sharedMaterial. I've looped through the main parent of the "creature" it's added to and debuged every name and it's just not added. Which means for all intents and purposes I can't get at it without checking the whole scene.
I'm sure there's an easier method that's more performant but it happens once, when you're not even able to see what's going on.
Chestplate 1 is what I need, that has the SMR.
is this some modding bs or can you not just look through your own code to see where it may be instantiated from?
It is some modding bs
then go ask for help in the game's modding community
I'm asking how to loop through gameobjects in a scene without inheriting from monobehavior, not how to do my specific thing
and your question is because you want to do that specific thing instead of figuring out how to do that thing correctly
Do you even know if it's the correct way?
What you're doing is most definitely not the correct way
i can assure you that iterating through every single object in the scene is very likely not the correct way
which I did acknowledge*
GameObject[] allObjects = UnityEngine.Object.FindObjectsOfType<GameObject>();
I'm only curious how
I believe
Thank you 😭
Don’t ever do this though
The scene directly has a method to get root objects
I am fully aware it is a horrible idea to do it
Which boxfriend already answered on
Thanks for the help everyone, it worked 😮
once i changed the type from GameObject to something more specific, i was able to call methods in the instantiated object's script
then i passed a function reference to the instantiated object, which it could call when it got an onclick event
The best method would be to add a monobehavior in the editor and just use that, but i can't
Which method do you want to use from monobehavior?
Also couldnt you just GameObject.Find it based on name?
No specific method really, just being able to add it to the exact gameobject and reference everything I need would be perfect
I see.
Naming variable m?
well it should, considering you ignored the actual suggestion on how to get a gameobject by its name
Which suggestion?
If you are just doing this use GameObject.Find, as Bawsi said
So you don’t have to iterate
well ignoring, not reading, about the same thing. Boxfriend did answer your question as well for what you initially wanted #archived-code-general message
but really, ask questions like this to the games modding community. either they have a system in place to get you exactly what you need, or they'll tell you to use GameObject.Find
I did ask them, I asked the people who made the game
Well, one of the devs, not all of them
GameObject.Find also did not get the GameObject, I debugged it and it was null.
then that object was either inactive or non-existant at the time you called it. or you spelled the name incorrectly
Hi, for some reason I am unable to paint on terrain, any possible reasons why this may be?
This is a coding channel #🔎┃find-a-channel
If you're doing it with code then you should specify and show relevant code
A friend of mine is talking about dropping her course bc she struggles to remember code and has to watch a lot of tutorials for coding
I keep telling her, there's no shame in following videos but its a real weight 😦 sad
I was the same in uni, most of my course I spent following tutorials
i'd quit that school immediately, you'll learn nothing there
I graduated a year ago
And no I meant like
I struggled to remember my classes so anything I made for fun, I would watch video tutorials to supplement what I couldnt remember
The classes werent just watching videos, good lord
if the school doesn't force you to understand the concepts and apply them to problems for which no tutorials exist, you have not spent your time well
Oh my God
Kurwa
I just mean like forgetting the syntax, not the concept of implementation
When I'm writing in HLSL, and I forget a line, I just look up a tutorial
Its stuff for fun not training for the Air Force
why aren't you looking at documentation?
I don't understand how to fix some flaws in this script. Today I can't think like I would usually. I have been stuck on this for quite some time now. How can I make it so it doesn't drop the current weapon if it is not the same type? I have 3 types of weapons, Primary, Secondary, and Melee.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
now?
yes, if you want people to read your code, post it correctly
Ok
Is there a way to hook directly onto the space partition unity creates for the physics simulation?
no
disappointing, thank you
that's what happens when you use a game engine
Unless it is open source :P
Anyone using an open source engine and is sufficiently competent to modify it would not be posting basic questions on discords
jeez guy
or you pay for the enterprise or higher tier 🙂
lol
Hey can someone help me with this:
I'm trying to record the plays each player makes in my game for later debugging and other purposes and for PC this is pretty straightforward, I just give a filepath and done. My issue is with the Android build, the path that I use (Application.persistentDataPath + wtv name) is not easily accessible, is there a way for me to use/create a more accessible folder on mobile?
Code for ref:
private void Start()
{
// Determine the folder path based on the platform
#if UNITY_ANDROID || UNITY_IOS
_writeToFolderPath = Application.persistentDataPath;
#else
if (string.IsNullOrEmpty(_writeToFolderPath))
{
// Set to a default path inside the game installation folder if no path is provided
_writeToFolderPath = Path.Combine(Application.dataPath, "GameRecords");
}
#endif
if (!_writeToFolderPath.EndsWith(Path.DirectorySeparatorChar.ToString()))
{
_writeToFolderPath += Path.DirectorySeparatorChar;
}
string fileName = $"GameRecord_{DateTime.Now:yyyy-MM-dd_HH-mm-ss}.json";
_filePath = Path.Combine(_writeToFolderPath, fileName);
// Ensure the directory exists
try
{
if (!Directory.Exists(_writeToFolderPath))
{
Directory.CreateDirectory(_writeToFolderPath);
}
}
catch (Exception ex)
{
Debug.LogError($"Failed to create directory {_writeToFolderPath}: {ex.Message}");
this.enabled = false; // Disable the script if directory creation fails
return;
}
}
That path is accessible just fine - but you have to use UnityWebRequest to read/write files on android
unless you mean something else by "not accessible"
btw with cs if (!Directory.Exists(_writeToFolderPath)) { Directory.CreateDirectory(_writeToFolderPath); }
You don't need the if statement at all
hm, I literally mean by hand go into file manager and grab it. File manager doesnt seem to allow me to get there
what is file manager
the normal phone app file manager
Sounds like some particular app
Why not just grab it through ADB
Is it possible to be able to assign a script in the inspector for another script to run a function in? I have a basic UI manager script and it would be convenient to be able to write a separate script for whatever each button does, then run a function in that script through the UI manager (probably explaining this very poorly, sorry)
You can assign an instance of a script to do that with
but maybe you're asking about UnityEvents
not exactly what I was looking for but I can definitely work with this, thanks
The first thing you asked for just sounded like a basic reference.
What I meant was to not have to specify the exact script in the manager, so I could write different scripts after to do different things
but again, this should work
Why is unboxing faster than boxing? Is it because boxing involves creating new objects which take time? Is that it to the discussion? In an interview I was asked what the relation between GC and boxing/unboxing was and the only thing I could come up with was that boxing involved creating new Object objects which required memory allocation on the managed heap, and nothing else(that I know of that's related).
yes boxing allocates new memory
or rather a new section of the heap
it's creating an object
mhm
unboxing is just dereferencing the pointer
