#archived-code-general
1 messages · Page 249 of 1
Yes
i actually tried that. but its so bad like that, because the translation would be affected by the scale.
unlikely
Well, the translation shouldn't be affected by the rotation
yes.
im not sure. maybe unity does it in a different way or sth ?
i actually tried all the possible combinations. none acted right.
//_localMatrix = translationMatrix * scaleMatrix * rotationMatrix;
//_localMatrix = translationMatrix * rotationMatrix * scaleMatrix;
//_localMatrix = scaleMatrix * translationMatrix * rotationMatrix;
//_localMatrix = scaleMatrix * rotationMatrix * translationMatrix;
//_localMatrix = rotationMatrix * translationMatrix * scaleMatrix;
//_localMatrix = rotationMatrix * scaleMatrix * translationMatrix;
you are right, should be (T*R*S)*P
Yeah, should be. The problem is in that code though, Unity does what makes sense
Actually pretty sure it should be T * (R * S)
mul(translationTransform, mul(rotationTransform, scaleTransform)).
let me think and see
bool CanShootCheck() {
bool check = Physics.Raycast(camera.ViewportPointToRay(new(0.5f, 0.5f, 0)), out RaycastHit hit, 2.5f, groundMask);
if (hit.transform && hit.transform.CompareTag("Sphere")) {
if (hit.transform.GetComponent<Rigidbody>()) return check;
else return !check;
} else return !check;
}
Do you guys think you could help me optimize this function?
Is there a performance issue with it...?
No, it just feels a little sloppy
I'd like to see what I maybe could of done different 🙂
not rly.
I suppose the Unity mathematics package is just wrong then https://docs.unity3d.com/Packages/com.unity.mathematics@1.2/api/Unity.Mathematics.float4x4.TRS.html
if the hit.transfrom not null then check must be true?
it may throw a NullReferenceException
you can fallout of the statement and still return !check but otherwise nothing really to optimize here and I wouldnt worry about it
maybe. but then unity's classic TRS returns the "right" or rather the "intuitive" position ? im a bit confused
@gray mural How so? Are you referring to if (hit.transform)?
yes
@latent latch Could you please provide an example?
Already checked for this, no problems here!
you return !check twice but you only need to do that once
you can get !hit, can't you?
@latent latch I have to do that because not all paths return
That's what I've been saying. Unity's output makes sense
I haven't looked into your numerics TRS logic, but it doesn't make sense that the position you get out of TRS would be anything other that what you put in
you want to return true if nothing is hit?
if hit is null, then hit.transform throws an exception. With if (check) you make sure it doesn't happen
hit cannot be null, it is a struct
Don't worry, this does not occur 🙂
if(check){
return hit.transform && hit.transform.CompareTag("Sphere")&&hit.transform.GetComponent<Rigidbody>();
}else{
return true;
}
I see, you're right
@fervent furnace Let's try this out!
oh, i am wrong
😮
let me think about it
if hit.transform !=null then check is true, that means if transform.comparetage is falas it returns !true=false
if they are true then return true if there is rigidbody, !true if no
so transform&&tag&&rb should be correct, if trsnsform is null that means check is false, return !false=true
Checking hit.transform is redundant if you've checked check
If it hit something, it has a transform
you are right, remove the hit.transform
return !check||hit.transform.CompareTag("Sphere")&&hit.rigidbody;
```one line
Also didn't hit have a rigid body field?
yes
I was just writing this xD
Thanks!
Awesome, this is great!
Hello! Im trying to set a variable of an instantiated gameObject, but unfortunately I keep getting this error. Can anyone help me a little?
It might help if you included lines numbers. also !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.
not code general
is line 22 answer.text=text?
updated
so answer is null
have you set it in inspector?
i thought so
line 35, second script
that sets a local varaible
dont just think, check it
second script is irrelevant
should I make it public?
how do you declare answer in the first script
check first line in there
so how do you expect it to contain a value?
so did you make the variable reference an actual TMP_Text object (component)?
i forgot to set it in inspector, since its a prefab, should I use GameObject.find?
is the text on the prefab or some gameobject on world eg canvas
on prefab
an I like used a canvas on the prefab in order to add the text is that okay?!
you might be better using dependency injection.
Can the second script which does the Instantaite get a reference to the first script?
whats that
he says the text on the prefab so he can just drag the component and drop it to the field
so theres no need for a canvas
but he want a reference to the instantiated object not the prefab
how can I have a text without a canvas, or is that evenm possible?
@swift falcon Dependency Injection
...
Script1 needs a reference to answer
Script2 instantiates answer
Gets a reference to Script1
script1.answer = answer
Yes, TMP has a non canvas Text version
teach me
should still work
doesnt work, also script 1 is ran on the instantiated object and I want to modify the text being its child object
No active UnityEngine.XR.ARSubsystems.XRCameraSubsystem is available.
Anyone knows how to correct this error?
then you can just set it in the inspector of the prefab. you should have mentioned this important fact earlier
yea, but even with the text set, it wont work
its an issue with the txt string
since I looked at an instantiated object, it had the answer value set
so the null ref has now gone?
then it has nothing to do with the text string
show the inspector of the script
this is not a code problem, it is a setup problem
Spawns the answer https://paste.ofcode.org/W6DKufUYJvSenjTYcTWfTZ
Runs on every answer https://paste.ofcode.org/fYUXriVyBqq8CghEvVu25G
alright one sec
in the second script from above, its value is set
and answer has not been set
*I meant answer here
you need to set variables here
they are set at the beginning of start()
which is obviously not working, set answer in the inspector and not in code
it worked, but why???
why not in code?
you get NRE => your code not work
obviously something wrong with your logic of where the component is
run doesnt mean work
btw hardcoding like that is very bad practice and often prone to break as you have found
I have a problem. I throw Raycasthit2D.hit.point at some part of the gameobject (a platform for example) and apply it to Springjoint2D.connectedAnchor. This is how i implement a grappling hook. But problem is, when this platform is moving, my player stays on the same position and i need to move it with the platform. Transform.position of this platform is not a solution, because it is the position exactly on the center of the platform, whereas i was attached on the corner of the platform, for example. How can i update connectedAnchor accordingly with the movement of the platform?
anyone know how to edit post process volume settings at runtime?
can't seem to find good info on this online
- How can i change the float value type to int? I'm not looking for casting, that'd mess up the bits order within the float. I need to preserve the bits sequence while changing their type to int
- The only solution i can think of rn is a struct with explicit memory layout. Any other solution?
You can use System.Runtime.CompilerServices.Unsafe.As or Unity.Collections.LoweLevel.Unsafe.UnsafeUtility.As to reinterpret cast:
float f = 0.55122f;
int i = Unsafe.As<float, int>(ref f);
Hey everyone, I have a git question.
I added the first .gitignore file I found on Google but now when I run git status I see the following weird files/directories:
ProjectSettings/EditorBuildSettings.assetAdaptive Performance/Adaptive Performance.meta
Are .meta files and the rest of the listed ones necessary to be tracked in git?
.meta files are very important
public List<BuffTarget> buffTarget;
public List<int> buffAmp;```
any way to "combine" variables so I wont have to fiddle with 3 different lists?
impossible if you cant cast one to other or using object everywhere
btw i remember this way should work, let me check
float x=???;
int y=*((int*)&x);
The animation is running but after completion it is not coming back to the idle state. The normalizedTime condition looks right?
Unless I'm misunderstanding the question, you can use a tuple or a struct that contains each variable:
public List<(BuffManager.Buffs buffs, BuffTarget target, int amp)> buffs;
or
public struct BuffInfo
{
public BuffManager.Buffs buffs;
public BuffTarget target;
public int amp;
}
...
public List<BuffInfo> buffs;
you can warp like this but you need additional check
unless he want to group the value together
What about Adaptive Performance?
It's probably a folder where settings related to Adaptive Performance will be stored, which you want to track.
I'm trying to learn compute shaders, but I can't figure out how to calculate the range that SV_DispatchThreadID will give. The Microsoft docs give a formula, but trying it in Wolfram Alpha doesn't work. I'm probably using the wrong operations, so does anyone know the right ones?
Isn't it just based on the xyz dimensions you pass in here? https://docs.unity3d.com/ScriptReference/ComputeShader.Dispatch.html
According to the Microsoft hlsl docs:
SV_DispatchThreadID is the sum of SV_GroupID * numthreads and GroupThreadID
Right so it's basically the (x,y,z) from your kernel itself scaled by the xyz you pass into dispatch?
It's been a while since I used compute shaders
- Iirc unsafe context won't compile in unity?
I think so. I get where the numbers are coming from, but this picture from the microsoft docs disagrees with the result from wolfram alpha
Unity.Collections.LoweLevel.Unsafe.UnsafeUtility, full of pointer stuff
sounds pretty unsafe
basically C programming
I think I figured out that it's just supposed to be the Hadamard product
In mathematics, the Hadamard product (also known as the element-wise product, entrywise product: ch. 5 or Schur product) is a binary operation that takes in two matrices of the same dimensions and returns a matrix of the multiplied corresponding elements. This operation can be thought as a "naive matrix multiplication" and is different from the...
Right which is what I meant by scale
oh that makes more sense
As far as assemblies go, is there a simple way for me to make one asmdef that is then equivalent to what I currently have in my project, which is C#-assembly default assembly?
my plan is: 1) make my own giant equivalent C# assembly, 2) slowly break it up into smaller assemblies where each assembly I add keeps everything working properly
If you put an asmdef at the root folder of where all your scripts are you'll get this
i tried, but DOTween is not happy with this because it has its own .dll
i think I’ll give it another shot tho
so... all my scripts are in subfolders of Assets. Therefore, if I put an asmdef in Assets directly, everything should still work?
Yeah I'd just move all your own scripts into a folder not mixed with any packages or assets
DOTween will need an asmdef too though
step 1 is to make a giant assembly where everything is working. Then slowly split everything up in a way this is non-stupid
And you'll need to reference it
Hello, are there any peformance differences between Physics.Linecast and Physics.Raycast?
If the length is specified they would be practically equal right?
probably the last thing you should be worrying about tbh
yeah, just wondering if there are differences
Im trying to connect a mysql database to my unity game, so I imported the connector mysql.data.dll file and the system.data.dll file but I get the error message:
they do the same thing in the end only the parameters are a little different
what's the difference
yeah they just do different things
seems like linecast just returns a bool?
which version of MySql.data ? Version 3.5 is the best version for unity projects
I'd say they can be used interchangeably, it depends on what data you have as input.
Raycast takes in a start point, direction, and distance
Linecast takes in a start point and an end point
so performance probably doesn't matter if you use nonalloc
my connector shows NET 8.2.0
oh, wait there is a overload method with a rayhit
no way that is gonna work
yes, if you cant find it, DM me and I'll send you a copy
about that, my unity only shows 2.1 and Net framework
i dont have 4.x or 3.5
I put an asmdef in the root Assets folder, but now none of my scripts can see anything in Packages, and it doesn't look like unity lets me add an asmdef to it. Is there a way to make the packages a dependency?
or do I just need to manually add every single package in my project as a dependency of a given package asmdef or something?
.net standard includes 3.5 or 4.x
.net standard is not the same as .NET
you have to manually add every package you want to use
ok. that sucks, but at least I have a plan.
How to get position of some part of the gameobject? transform.position return the center of this gameobject and i can throw raycast to some part that not the center and i need to return this as local position on this gameobject
you need to have some way to reference it
which part of it you want?
like using the bounds of a collider, or a separate child gameobject, or a fixed offset vector saved for that gameobject
collider bounds is kind of shit, so I will frequently go by the dimensions and offset of the collider
eg: transform.position + boxCollider.offset + boxCollider.size….
or whatever
@rigid island for example, i throw raycast that hit this gameobject (a platform object, to be precise), return .point as Vector2. I hit closely to the corner of this platform. I send this to Springjoint2D.connectedAnchor. This is how a grappling hook works. BUT when the platform moves, my player stays on that point which i hit previously on the world space and not with the platform.
it sounds like you need a conversion between local and world space
I can bind it to transform.position, so when it moves it updates to it, but is it the center of this platform, and i need to update position exactly on that part i hit on the platform
ok there’s a lot to unpack here
if you have a springjoint2D, then it should be linked to a rigidbody
create the offset and when you move make sure you move the point with platform
it sounds like you just want the springjoint2D to be offset to target a specific point relative to rigidbody position
Recently the mechanic doesn't rely on the rigidbody and connectedBody property. I need to update connectedAnchor
Dynamic, it moves
And has velocity update
is connectedanchorpoint in local space or world space? I’m not too familiar since i’ve had to scrap joints before
if you need to recompute the point every frame, you just need to use a transform method to convert
World
that is bizarre, since I feel like that defeats the purpose of a joint2d
but either way:
platformTransform.InverseTransformPoint(pointYouHitInWorldSpace) gives you the local space point of where you hit. and you would save this as the grappling hook’s offset
platformTransform.TransformPoint(localPoint) gives the world pos
then the connected anchor point does not sound like world space
It is, raycasthit2d.point returns exactly this
the whole point of a Joint2D is to apply constraints that affect DURING physics simulation. It would be nonsensical if you had to specify the joint to target a spot in worldspace
yes, but we’re talking about the joint’s connectedAnchor point
raycast will always give world space, because physics queries always exist in world space
the joint should only care about relative space
Ok i see now, connectedAnchor is local
Joint2D don’t have business dealing in world space
i just didn’t know how the field output it
either way, you need to take your hit position (world pos of grappling hook), and convert to local space of platform with platformTransform.InverseTransformPoint
this gives the point in local space of grappling hook, which is also the offset for the spot we need to connect
I checked, it says that connectedanchor is world pos when no rigidbody connected
And my springjoint doesnt connect to rigidbody
that makes no sense
I get confusion
because you said it breaks when your platform moves
but why are you moving your platform if it lacks a rigidbody
Yes, but it doesn't apply as connectedBody
i don’t see what the problem is
if you move the platform, it needs a rigidbody.
if you want to joint your dynamic rb to a kinematic rb, the joint needs to know both RBs as targets
then when both move during physics sim, simulate will apply a constraint between the two RBs to apply force between them, as it tries to satisfy all the conditions of your system (eg position, velocity, time, force, mass, collisions….)z
does this make sense?
is there something equivalent to quaternion.identity for a 90 degree rotation or 180 degree rotation?
90 degree rotation doesn’t make sense in 3D. Do you mean 2D?
oh yea
either way, I think there is Quaternion.Euler
im just using Quaternion.Euler(0,0,90) rn
ah
You could make a static class with some preset values, I guess
quaternions can multiply btw
also does Vector2.down depend on the rotation of the gameobject or does it always just point down relative to the world space?
transform.rotation *= Quaternion.Euler(0,0,90f);
ah is there a way to get the direction that the gameobject is facing?
transform.up, transform.left…
transform.TransformDirection(Vector3.down)
-transform.up
These are equivalent.
ty
Absolutely makes. But as i said, my mechanics of the grappling hook only relies on connectedAnchor, i doesn't apply to connectedBody, i never connect to any rigidbody EVEN though these platforms have rigidbody and moves. Because i attach my hook to raycasthit2D.point which is world position. I don't want to rewrite this mechanic, and that's why i ask how to update position to connectedAnchor relatively to the moving platform
annoyingly, there is no transform.left or .down or .back
rip
use an if statement lmao
so do u just need to rotate the transform manually then?
like do transform.up and then rotate based on what u want?
if (attaching to moving platform) set rigidbody and calculate local position;
else connect to world pos
you do not want to connect two rigidbodies together, by shittily just tracking behind some position.
Ok, i'll try
i don't know what you're aksing
for example if i wanted to get transform.right
if you want to get the direction you're facing, just do transform.right or transform.forward or whatever is the "facing direction"
i can guarantee that what you were asking for (recalculating world pos every frame without jointing the RBs) will lead to jank
sorry i misunderstood
I have a ramp that uses the Floor physics materrial. No matter what I adjust the static friction to, the player either slides off the ramp if the static friction is too high, or the player starts moving backward when I try to make it go forward if the static friction is too low.
if the dynamic friction is zero, that means that moving objects will be frictionless
note how you've set Friction Combine to "Minimum"
so no matter what the friction is on the other object, you're getting 0 dynamic friction at all
(assuming that one's physic material is set to Average)
But if the dynamic friciton is anything greater than 0, when I try to make the player go forward, the player instead goes backward because of the friction
unity friction is ass. i basically always set it to zero
but this also means having to set gravity to zero on slopes/grounded
does anyone know what causes all the materials in my asset bundle to be loaded invisible while using universal render pipeline? and is there a way i can load it or build it differently possibly to not have this issue?
Are these the values that you set for the rigidbody of a floor?
why does your floor have a rigidbody if its static?
Tbh I forgot the original reason as to why I put it there. Should I remove it?
Do these values look good for the physics material?
I want to apply it for a ramp that the player can walk on. No matter what I adjust the static friction to, the player either slides off the ramp if the static friction is too high, or the player starts moving backward when I try to make it go forward if the static friction is too low.
And same goes for the dynamic friction
it might be better to apply the physics material to the player itself then
and keep all other ones as is
you can adjust/swap out the physics materials based on the players moving state too then
I currently have a player physics material applied to the player
just use that, reset the other one
and set the friction on both settings for the player to 0
But now the player slides off the ramp
so, replace the physics material on the player so that when they arent moving, the friction is increased to 1
so the player's physics material is going to change depending on if it is moving or not?
yeah
Should I do it based on input, like if the player is currently holding down the key that causes the player to move, the player's phyiscs material switches, or should I detect if the player's rigidbody is currently moving, and then switch physics materials based on that?
i use rigidbody2D
very different
I have a controller for the cube to rotate for example 90 degrees right if im moving right , 90 degrees forward if im moving forward, and an animation separately to give it a jump animation but it doesnt seem to work
it just goes lower and lower into the platform
should just post the code
{
isMoving = true;
playerAnimator.speed = 1*(1 / moveDuration); // Synchronizes the speed of the animation to match the speed at wich the player moves
playerAnimator.SetTrigger("Jump"); // Adds the jump animation (y from 0 to 1 and back to 0)
Vector3 initial_pos = player.position;
Vector3 target_pos = player.position + direction;
Quaternion initial_rot = Quaternion.Euler(player.eulerAngles);
Quaternion target_rot = Quaternion.Euler(new Vector3(direction.z*90, 0, -direction.x*90));
float duration = moveDuration;
float elapsed_time = 0f;
while(elapsed_time < duration)
{
player.position = Vector3.Lerp(initial_pos, target_pos, elapsed_time / duration);
player.rotation = Quaternion.Lerp(initial_rot, target_rot, elapsed_time / duration);
elapsed_time += Time.deltaTime;
yield return null;
}
player.position = target_pos;
player.rotation = Quaternion.Euler(Vector3.zero);
isMoving = false;
}```
is there a way to debug and "see"/know what is modifying my player position
i checked all scripts, rigidbodies and colliders, and my player is moving down in a moment were it shouldn't, i cant find what is "making it going down"
without any of the rotation, it seems like your animation keyframe starts in the middle and ends lower than the first
starts at 0
ends at y 0
in the middle its y:1
i removed rotation it still goes down
let me see if i just do the animation no movement
Oh i think i found it
if you look at the blend tree it starts at the middle
but the next iterations start at the beginning
(also the fact it never completes a full animation cycle) oh, Im looking at the wrong block, half asleep here
i thought it had to do with the direction i passed in the coroutine but it is normalized so it wasnt that
yeah im not too sure, but the animation is from 0 to 1, but your first iteration goes for 0.8 to -0.2
what makes it confusing is you're doing some positional logic in the animator but some in code
so perhaps there's some confliction on the timing/positional values between the two
what I'd do is trigger the jump, await the clip, then proceed with the rotation and movement to the next spot
or perhaps just make them both animation clips
Hey guys, how are you? Can anyone help me with a question, or advise me on my project: I'm creating an EnemyIA that will use A* pathfinding to find the target, so far so good. My problem is how can I do it for large maps, as it would take a long time to return the calculation and this could cause slowness. The idea I had was to create several grids, each representing a region of the map, so I wanted to find a tutorial that could shed some light on this and also here on the discord channel.
it is called hierarchical search
almost all methods for reducing run time of graph algorithm is to reduce number of vertices and edge
Hierarchical search, does it have another name? Because I'll try to find out on YouTube or Google.
It sounds familiar to me, but I'm not sure what to call it
It's almost like LODs for your navmesh
one big low-fidelity graph for long-range calculations
I found it, but it's not about create a map and divide it in grids, i'm looking for the name of this process
and then another high-fidelity graph for navigating up close
https://www.youtube.com/watch?v=hKGzSYXPQwY&t=84s&ab_channel=SasquatchBStudios im using this video to learn to use unity at 2:08 is a script and when i copy it in unity it says its wrong why
Unity Asset Store BLACK FRIDAY Sale - EVERYTHING on this page is 70% off:
https://assetstore.unity.com/?flashdeals=true&aid=1100lwgBQ
Join our Discord Community! - https://discord.com/invite/aHjTSBz3jH
Show your Support & Get Exclusive Benefits on Patreon (Including Access to this project's Source Files + Code) - https://www.patreon.com/sasquat...
that is extremely vague
the second screenshot has quite a bit of code that isn't in the first one..
what is the codeee?
thats missing
and line 28 is half-finished in your second screenshot. that's not a complete expression
are you unable to compare the two scripts yourself?
Ok, thank you, if you know more about, just call me
@heady iris look at both my codes whats wrong with them?
i used chatgpt and it said the code has nothing wrong with it
you changed your script in between sending this image and the new image. line 28 now looks okay
however, it also looks like !ide is not configured. please follow the instructions in the bot message below:
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
no i just didnt send full screenshot
actually...i'm bad with colors
damm
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class FlyBehavior : MonoBehaviour
{
[SerializeField] private float _velocity = 1.5f;
[SerializeField] private float _rotationSpeed = 10f;
private Rigidbody2D _rb;
private void Start()
{
_rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
if (Mouse.current.leftButton.wasPressedThisFrame)
{
_rb.velocity = Vector2.up * _velocity;
}
}
private void FixedUpdate()
{
transform.rotation = Quaternion.Euler(0, 0, _rb.velocity.y * _rotationSpeed);
}
}
this the code
Which of these is your code? I don't know which one is yours and which one is from the tutorial.
i think that answers my question, haha
Your code editor is not configured properly. You should be getting auto-complete when typing, and errors should be highlighted with red squiggles.
why is that not happening? and how to fix?
my IDE is on the right. notice how i've got colors
!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.
Oh damn. You're checking the IDE
Sorry, screenshots make sense in that case
yeah
i already have it installed the unity and c# on my visual code
should i just install visual studio community?
First, go back and make sure you've followed every step
i have
99% since i did it twice
Go back and check each step.
Make it 100%.
Then close VSCode and click this in the External Tools settings screen
If it still isn't working, show me screenshots of your package manager and of the External Tools settings
alr
in unity?
or vs?
If you don't know where that settings screen is, I don't think you followed all of the instructions.
i dont think thats before 2:10
in the video
This has absolutely nothing to do with the video
oh
alr
@heady iris
what does that mean
@heady iris
why has this happened now
(i fixed the code)
Hi folks - is there a way to retroactively apply a root namespace after applying it in project settings in unity? Can't seem to find an answer to this one on other postings. I have all my scripts in my Script folder and subfolders, but is there a way to add that root namespace en mass?
I recently added this code into my project: ```c#
public void Login()
{
Debug.Log("here");
IList<object> names = GetColumnValues(sheetsService, spreadsheetId, "Sheet1", "A");
int row = names.IndexOf(usernameInput.text);
string correctPassword = GetCellValue(sheetsService, spreadsheetId, $"B{row}");
passwordEncrypted = GetHashString(Password.text);
Debug.Log(correctPassword);
}
Sounds like you forgot to add an Event System into your scene
I was looking at the event system and realized when I was clicking on the login button I was actually interacting with a ui elament that behind it. But now I am confused becuase it belongs to a diffrent canvas group that is disabled (alpha = 0 and is not interactable)
does someone knows how could i resize the right boxhelp in realtime with the left boxhelp? this is the code of both of them https://paste.ofcode.org/8YEY8kfyrSEqxptRJyjQgn
why when i call the method nothing happens i want to change the weight of this but nothing happens
I mean the first thing to do would be to add Debug.Log or attach the dbeugger and make sure the code is running
oh - data is a struct. You need to copy it, make your changes, then assign it back again.
structs are not references, they are value types
Wonder why it isn't erroring like it would when doing transform.position.x = 42
Is data not a property?
not for me?
not for you what? Those messages are definitely for you
Maybe it's like the particle system module shenanigans lol, where it magically references the original data
okay
You could give it a GUILayout.Height and store the value as a variable so you can use it on both, or put both in a EditorGUILayout.HorizontalGroup and set both the left and right to GUILayout.ExpandHeight(true), then they should match whatever height you set the horizontal group to - there is also a #↕️┃editor-extensions channel you can try for more suggestions - and as a small sidenote, you can use scopes instead of "begin/end" for layouts, such as
using (new GUILayout.VerticalScope(...))
{
}
Where the "..." would be where you can define GUILayout stuff and optionally an EditorStyle, its a bit more organized, and in VS you can collapse these scopes, I believe it may also have some performance gain if that becomes a concern for you, since you can cache them as well
Oh, I'll try it... Thanks for that advice hehe, now it's too difficult for me to know where every begin/end are located on the code... It's a bit chaos... Thank you so much 😁😉
My player is able to walk on flat surfaces, but it is unable to walk up sloped surfaces. How do i fix this?
private void FixedUpdate()
{
if (inputMovement == 0)
{
// Set the gameObject's Collider physics material to stationaryPlayer
collider.material= stationaryPlayer;
}
else
{
// Set the gameObject's Collider physics material to movingPlayer
collider.material = movingPlayer;
}
// Movement
rbody.velocity = new Vector3(inputMovement * walkSpeed, rbody.velocity.y, 0);
............
}
well you have a crapload of friction
that's going to make it difficult
this tutorial helped me a lot to deal with slopes, maybe you will have to adjust some stuff from your player controller but it is worth to watch it
https://www.youtube.com/watch?v=QPiZSTEuZnw
Discord Server:
https://discord.gg/uHQrf7K
Project Files:
Github: https://github.com/Bardent/Rigidbody2D-Slopes-Unity
Google Drive: https://drive.google.com/drive/folders/1qxFq3EBkU0JLu_iwXOtEc9-dW6_C1SpL?usp=sharing
If you wish to support me more:
https://www.patreon.com/Bardent
---------------------------------------------------------------...
Does this tutorial also work for 3D space?
it can work for 3D but you will have to listen carefully to the youtuber explaining why things don't work and how he fixes them, there's nothing you can't do with a little thinking
https://docs.unity3d.com/2020.1/Documentation/ScriptReference/Tilemaps.Tilemap.DeleteCells.html
Why does this method delete every single tile in my tilemap?
room.Tilemap.DeleteCells(new Vector3Int(1,1), 1, 1, 1);
even when I have a lot more in the room.
The biggest problems with slopes is, generally your trying to move perfectly horizonal, into an incline, and gravity wants to push you back down, in most cases, youll want to try to move along the slope, rather than "into" the slope, im sure that video may mention that, for 3D you can take a look at ProjectOnPlane: https://docs.unity3d.com/ScriptReference/Vector3.ProjectOnPlane.html - though this may only be part of the solution
Try passing in 0 for the last param not 1?
I tried, but then nothing happens D:
should only delete 1 cube afaik
well I'm pretty sure that's the method to delete actual rows and columns
maybe share your code?
public class Starter : MonoBehaviour
{
public Room room;
void Start()
{
room.Tilemap.DeleteCells(new Vector3Int(1,1), 1, 1, 1);
}
}
public class Room : MonoBehaviour
{
[SerializeField] private Tilemap m_tilemap;
public Tilemap Tilemap => m_tilemap;
}
Hey, in my Option class I want to have a list of conditions. Each condition has one ScriptableObject which it compares to another SO (these SOs each only have a value). Each SO is either IntValue, BoolValue, etc.
Currently they don't inherit from a base class and neither do they implement an interface. Same goes for the conditions, IntCondition, BoolCondition, etc.
Now it makes my life hard, having to implement a list for each type of Condition/SO I have.
Condition classes should have a public bool method, which says if the condition is met. I only need multiple classes for each datatype, because they have different comparison operators... I would like to have conditions implement an interface, but then how would I be able to edit the List<ICondition> in the inspector? Is there an easier method than to just add tons of lists for each condition type?
public class DialogueOption
{
// want to have all of them in one list
// for expandability and structural reasons
public List<IntCondition> intConditions;
public List<BoolCondition> boolConditions;
}
public class IntCondition : ICondition
{
public GlobalIntValue firstValue; // GlobalIntValue is an SO
public IntComparison op; // enum to choose from (<, >, ==, >=, etc.)
// this enum is what seperates conditions
public GlobalIntValue compareVariable;
public bool ConditionIsMet()
{
switch(op) { ... }
}
}
public class BoolCondition : ICondition
{
public GlobalBoolValue firstValue; // GlobalBoolValue is also an SO
public GlobalBoolValue compareVariable;
public bool ConditionIsMet()
{
return firstValue.Value == compareVariable.Value;
}
}
You need to mark your classes as [Serializable], and if you want them in a List using interfaces you can only use [SerializeReference], which by default will draw nothing for the null elements, so either you'll have to make a property drawer for them, or use a generic drawer for SerializeReference like mine.
Reposting here because I haven't really gotten a good answer or explanation in #📲┃ui-ux
I'm trying to recreate Yugioh Master Duel's deck builder UI. But I'm having trouble on the best way to implement it.
To me, it looks like most of it should be done using Unity's UI System. However, my cards are World Space Game Objects.
I want to programmatically create Game Objects of cards and display them in the UI container on the right, similar to Yugioh Master Duel's UI
In the screen shot, the White Boxes are UI Images, which work as expected. If I add enough White Boxes, the container will begin to scroll
However, the Red Circles are World Space Game Objects. They do not affect the UI Container at all. If I keep adding Red Circles, the UI Container will not scroll.
What are 2D game objects? You want to use rectTransforms with images
They're world space game objects
As if you created them from 2D Object -> Sprites -> Circle
But don't you still use rectTransforms on a world canvas, I'm not understanding
Or are you using a normal canvas but somehow childing actual transforms onto it
in that case you shouldnt and instead be using UI Images and taking a references from those world objects
There's a scroll view. The White Squares are UI Images, so when I add them, they automatically get displaced by the 10 px padding. If I keep adding them, the scroll bar will be able to scroll. But the Red Circles are World Space Game Objects, so they don't affect the scroll view at all and just appear on top
What do you mean by this? If you mean to just show my card sprite inside of a UI Image, that won't work because my cards are complex objects with several child objects and sprites. That'll essentially just show the card artwork, but nothing else
Here's what my prefab looks like btw
Sprite components shouldnt be on the UI. Sprite is Unity's way of batching 2D objects in the scene, but if you're using UI then you should be using UI components like Images
Yeah so that's where I'm confused
When you're actually playing the game, it's going to be using regular 2D objects in world space. Not UI
But in the Deck Builder, it clearly looks like UI to me
And if I want it to be responsive, then I think I should use UI
Then you have both, UI Images and 2D sprites but reference the same "Imported Image" for both components
But my card prefab is not UI, so I guess I need to mix and match them somehow?
Make two versions
Or have a fun time and calculate the world space positions and scales from UI objects and place the 3D versions there as if they were in the UI. Get the update order with UGUI layout correct (a nightmare), and avoid all cases where sorting with the UI is a thing
So I should create a replica of my MonsterCard prefab using UI components?
That is what I have done in the past
Is Yugioh's card game made in Unity? I know Hearthstone is if you've not checked that out.
Not sure what Yugioh is made in. Hearthstone is made in Unity, but their deck builder has a completely different design
Hearthstone also avoided UGUI iirc, just did it using meshes
Yeah, I know the game field is meshes, but I thought the deck builder was UGUI
but ive not played it for a while
Not sure if this is the right channel, but it does have something to do with programming.
If I merge two branches locally, and other person merged the same branches locally, will it cause conflict when the merged branches get merged in the future?
As long as you don't have any conflicting changes to any files you won't have conflicts
Alright thanks
How would you go about creating a grid and then having data associated with each grid location, i.e. (0, 0), (12, 15)?
In the past I've used a two dimensional array, but always have trouble with how to then associate the appropriate data for each array position. How would you store this data? Say for example you want each tile location to have a tile type associated with it. Land, ocean, etc.
2d array or flatten 1d array
and what is the problem of associate the data to index?
fancy way is to use quadtree
// Change pitch based on camera angle
float currentCameraAngle = camera.transform.rotation.x;
audioSource[0].clip = audioClips[0];
audioSource[0].volume = 0.75f;
if (audioSource[0].pitch > 2.5f) audioSource[0].pitch = 0.3f;
if (audioSource[0].pitch < 0.3f) audioSource[0].pitch = Random.Range(0.3f, 0.75f);
if (previousCameraAngle < currentCameraAngle) audioSource[0].pitch -= 0.065f;
if (previousCameraAngle >= currentCameraAngle) audioSource[0].pitch += 0.065f;
audioSource[0].Play();
previousCameraAngle = currentCameraAngle;
Hi again folks, just wondering if anyone could help me optimize this absolute spaghetti code. I've tried a method with Mathf.Clamp but I can't seem to get it right.
It works perfectly, but every time I look at this section I get the heebie-jeebies.
transform.rotation.x is nonsense
Have you actually tried debug.logging that?
It's not what you think it is
I only want to change the pitch whilst the camera goes up/down
That's not the part that I'm really worried about tbh.
It should be
It's fundamental to the whole thing
if (audioSource[0].pitch > 2.5f) audioSource[0].pitch = 0.3f;
if (audioSource[0].pitch < 0.3f) audioSource[0].pitch = Random.Range(0.3f, 0.75f);
if (previousCameraAngle < currentCameraAngle) audioSource[0].pitch -= 0.065f;
if (previousCameraAngle >= currentCameraAngle) audioSource[0].pitch += 0.065f;
This is literally the only part I have a problem with.
Believe me you have a problem with the rotation.x part too
Anyway it's really unclear what you want the relationship between the camera pitch and the sound pitch to be
But rotation.x is NOT any kind of angle around anything at all.
It is what?
Well it is.
It's a clamped value between -90f and 90f
It's a quaternion component
And will only give you a value between -1 and 1, and it doesn't represent an angle at all
Debug.Log it, you'll see
No, it gives me a value between -90f and 90f
Prove it, I don't believe you
I don't need to --- I just want help fixing those four if statements.
Just change camera angle to foo and bar if it helps.
The camera angle is not an issue here 😆
Well I addressed that part too #archived-code-general message
if (audioSource[0].pitch > 2.5f) audioSource[0].pitch = 0.3f;
if (audioSource[0].pitch < 0.3f) audioSource[0].pitch = Random.Range(0.3f, 0.75f);
if (foo < bar) audioSource[0].pitch -= 0.065f;
if (foo >= bar) audioSource[0].pitch += 0.065f;
This is literally the only part I have a problem with.
You'd have to explain what you want the relationship to be
foo and bar aren't making this anymore clear
Okay as the camera looks up/down, the pitch of my gun SFX goes up and down with the movement.
But with what relationship?
And has a reset value at a max of 2.5f, and a min of 0.3f
From that description just sounds like a basic remapping function
No -- that's not what I'm looking for sadly.
Well you haven't explained clearly what you are looking for
do you know what are else and ternary operator? google them
If you just want the pitch to change at a constant rate with the camera movement, why can't it be a simple mathematical formula?
btw idk why it minus/plus a constant no matter how the delta angle is
There's some other weirdness going on in there
If you could point me in the right direction this would be great!
It's not "no matter" it's based on whether or not the camera is pointing further "up" since the last time you shot. If so, it will increase the pitch. Otherwise it will lower the pitch.
It works perfectly fine 🙂 I was only hoping to see how I could of maybe achieved this result differently.
Could be something like this
function (var currentCameraAngle)
{
const absMaxCameraAngle = 100;
const absMaxPitch = .9;
var percentage = currentCameraAngle / absMaxCameraAngle;
return absMaxPitch * percentage; // new pitch
}
all my fellas, i require assistance. i'm using a character controller component to for my player object, and i want the player to increase in speed when the button is pushed to walk, and decrease in speed when the button is released. i've gotten this to work by taking advantage of the input manager and manipulating the settings there, but i'm struggling to get the movement normalized.
here i tried to use a method i'd seen online, it did not work.
https://paste.ofcode.org/NjkBb6ER6qS6MT2heMfxmL
and this does normalize, but it doesn't preserve the acceleration and deceleration when they move. it just becomes an instant stop and start
https://paste.ofcode.org/nWg7jmGGBpq2tp4Xv9d6JE
any insight would be appreciated lads.
Well that first link you're just ignoring the normalized vector entirely.
In the second link you're using it.
But I don't understand your question at all. If you want a smooth acceleration why would you normalize the vector?
Normalizing it is completely at odds with anything except full speed at all times
because i don't want the speed to increase more than intended when the player moves diagonally. i assumed normalizing was the simplest way to fix that
The correct way to do that is with https://docs.unity3d.com/ScriptReference/Vector3.ClampMagnitude.html
thanks for the info. what does normalizing do that's different?
Do you know what normalizing means?
apparently not since i was using it in the wrong place
A normalized vector is a vector in the same direction but with magnitude of 1. So if it was shorter than 1, or becomes 1 and if it was longer than 1 it becomes 1.
In your case you want to make vectors longer than 1 to be length 1, but you should leave vectors shorter than 1 alone
Normalize won't leave those shorter vectors alone, but ClampMagnitude will
so normalize just works in 0's and 1's then? it doesn't use anything that falls between them?
The definition of a normalized vector is a vector of length 1
The values within a normalized vector will be between 0 and 1. It's just the length will always equal 1.
oh that is different. now i see. thanks y'all
It forces the vector to land somewhere on the unit circle.
damn normalize really just says "fuck your number, you're getting a one"
Any tips on how I can procedurally generate a shape like this. I have a grid array already, but want to have a method generate a shape like this and then assign the values to each position, i.e. water and land. For now to keep it simple, I'm just using an int based grid so 0 = water and 1 = land.
I tried a few methods like creating it line by line with random ranges for the length of each row, but I can't get anything that looks natural.
I've got an architectural question. Really simple setup. Let's say I have some Money value, and a script called MoneyTrigger that wants to tick up the value of money whenever the player walks into a specific trigger collider.
I also have a MoneyManager script that handles the modulation of Money, (getting money, spending it, saving the value etc).
How best should I connect the MoneyTrigger and MoneyManager? I'd rather not require MoneyTrigger to have to slot in the Manager class in the inspector. I'd also not want MoneyTrigger to do something like FindObjectOfType. Making MoneyManager a singleton is also not really preferable.
The answer to most of these land generation questions is noise.
Lots of layered noise.
Sebastian Lague has a pretty good video series on the concepts. https://www.youtube.com/watch?v=WP-Bm65Q-1Y&list=PLFt_AvWsXl0eBW2EiBtl_sxmDtSgZBxB3&index=2&ab_channel=SebastianLague
Welcome to this series on procedural landmass generation. In this episode we create a grid of perlin noise values and render them to the screen as a texture.
The source code for this episode can be found here:
https://github.com/SebLague/Procedural-Landmass-Generation
If you'd like to support these videos, I have a Patreon page over here: http...
is your moneytrigger spawned in play mode? (not in world initially
Depends on the situation. Some yes, some no.
https://unity.huh.how/references/simple-dependency-injection
if some of them in the world already then i probably use findobjectsoftype to automate the process
Right now I sort of have a Pubsub set up. The MoneyTrigger can publish an event which contains the amount of money to be added. The MoneyManager listens for these events and updates its state based on the values in the event object.
If the Manager isn't even in the scene, then nothing happens.
A static event is an option
As long as you manage the subscriptions properly
I was about to say: though note that if you accidentally don't unsubscribe, static events are a fantastic way to get a leak
You could also use a ScriptableObject they both reference as an intermediary.
Funnily enough I wrap the PubSub itself in a scriptableobject 😛
Usually if communication is needed across a gameobject or to its children, I just use a serialized reference.
If communication is needed to a gameobject's parent, I use a UnityEvent or a C# event.
If communication is needed across "domains" (Game entities to Managers, Managers to UI etc), I use PubSub events.
anyone know what would be causing this
when i first pickup the weapon it goes into the right spot, but after i drop it and try to pick it back up it doesnt
you'll have to send the code in order for anyone to be able to help you. i'm going to guess the problem will be wherever you have the picking up and putting down programmed.
here's the code
Oh here's a method that might be useful.
https://docs.unity3d.com/ScriptReference/Component.TryGetComponent.html
Will help cleanup some of those null checks.
Hello i have an asset called Gamversion.asset and when making a build i want to increase the version(key value pair). How can i do that in Unity, i would like a static method i can call before making a bunch of builds?
Asset looks kind of like this
%YAML 1.1
...
MonoBehaviour:
...
Major: 0
Revision: 7 ```
using the advanced search, is there a way to select items with no components? I'm trying to batch grab all empty root gameobjects with no components attached. I can use "is:root is:leaf" to start, but not sure is there a 'not' option for e.g. 't:' ?
my files are gone in editor but in file exploror they are still there what happened help pls
i was just switching to webgl so i could put a build on itch.io for playtesting and they all dissapeared
but my game still works
someone please help me get htem back
Open and close unity ?
already done that
Reimport the project. Do you know how to do that ?
right click and reimport all
Yes
will that mess anything up though?
This isn't a code issue. Should be in #💻┃unity-talk
will everything still work as it did before
I think so
u arent a mod
Hello
i am having some trouble with the toggles
Re-import all just ... re-imports everything, it won't break anything
Sometimes it does
like isOn field is false
Yes now it will start reimporting everything
Hi guys, i'm kind of stuck and would need your advice.
I'm working on a personal project where i'm trying to blend two cubemap Skyboxes (day / night) and make it cycle from day to night in function of the IRL time (so the system time). I have the shader / blending part working. Altho, i'm stuck on the part where i need the "Blend transition slider" to slide to the right value. The slider can move between 0 and 1 max. So i had to normalized the time to get the right value between 0 and 1 (If it's 22:00 irl, it should be around 0.8 / 0.9 on the slider). But it doesn't seem to work right as it is 11:00 now and my cursor is randomizing around 0.003 and it should be around 0.5 since it's almost mid day. Since Day / night last the same, but Dusk and Dawn have smaller windows time, someone told me to use AnimationCurve, but can you really mix AnimationCurve and Shader Properties in a C# script ? To be honest i tried a lot of things and i think i confused myself.
Bonus : Mathf.PingPong is doing exactly what i want, but can't manage to make it happen slower (so related to irl time). Doesn't accept any surcharges of the function. Here is my C# code for the moment : https://hastebin.com/share/wataleneke.csharp
Thanks for the help
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
everything works now thanks
I'm getting the following error when trying to attach the script: The script is an editor script.
The script is not in the Editor folder, it worked just fine yesterday, and if I just copy the contents to a different script with a different name it works fine.
Is this some ridiculous problem with the metadata of the script?
Where abouts in this code do I need to add a 'mathf.clamp' to limit the rotation when I move left/right?
!code show it to us. You could also try just re-importing that file
📃 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.
TL;DR: The error was trying to attach a generic class that does not inherit from MonoBehavior to a game object. The error was message was completely wrong.
Tried it, tried resetting in git and whatever else, in the end the error was:
- I was trying to attach a script to a game object.
- The class in the script was generic and did not inherit from MonoBehaviour.
To this the editor raised the error "The script is an editor script", when I suspected that not inheriting from MonoBehavior was the issue I tried to inherit and it just said that the class name does not match the file name (even though in actuality the problem was that Unity does not allow generic classes to inherit from MonoBehavior).
Why on this one particular day is this singleton null for a few frames at first? Trying to add to the interestingObjects list when OnEnable is called in another script says that the game instance is null
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Game : MonoBehaviour
{
public List<InterestingObject> interestingObjects = new List<InterestingObject>();
public static Game instance;
public void Awake()
{
if (instance != null && instance != this)
{
Debug.LogError("Game singleton already exists! Destroying this copy...");
Destroy(this);
}
else
{
instance = this;
}
}
public void Update()
{
Debug.Log(instance);
}
}
Awake does run before OnEnable which is why this is puzzling
the scripts run like this:
A awake->A onenable->B awake->B onenable
awake runs before onenble is correct, but it may run after others onenable
That's really annoying. Is there a way to change this at all?
change script execution order/access it in start, start is guaranteed run after all awake were run
Never really fiddled with script execution order but I'll have a look around. Cheers
The compiler is not included outside the editor. There is no reason for it to be included.
https://docs.unity3d.com/2019.2/Documentation/Manual/webgl-debugging.html
FS.syncfs(false, function (err) {
console.log('Error: syncfs failed!');
});
They say to write this code, but there is no other information about it, what is FS?
Guys, how can that return 0
: (actual time = 14.0f)
hour = ActualTime / 12.0f;
ActualTime is an integer probably
it is not
or hour is an integer
Not too
then actuaTime is not 14.0f
I swear, i tried everything, it still returns 0
then type 14.0f / 12.0f and see the result
Returning me the right float with decimals. BUT HOW.
I'm gonna hard paste that here
look
[Header("24h Format")][Tooltip("24h format")] public float ActualTime = 14.0f;
[ReadOnly][Header("12h Format")] public float hour;
I even tried casting the variable in float by doing (float)ActualTime / 12.0f. Still 0
Use debugger
No errors.
by putting breakpoints ?
yes
You've declared it as 14, but what value is in the inspector?
0 currently...
Well there you go. Not complicated
oh it serialized it to first value you set it to
[NonSerializable] would fix it probably
Let me try
No way. Since when does it serialized it by default or either take the value from the inspector before the hard coded value ?
(It worked)
afaik any value you give it at the start and then compile will be serialized
it should only apply if you have a value serialized in the inspector(defautl behavior for public variables)
public int Hour;
[SerializeField] private int Hour;
Those are seriaized(visible in the inspector)
[NoSerializable] public int Hour;
private int Hour;
Those are not serialized(not visible in the inspector)
Always
So, to make my variable take the changes i do in the code, it would need to be hide in the inspector so no serializable ? what the hell
yes, because if you use inspector to setup some numbers, you dont want them to be lost when you make some changes in your code.
I don't remember having those issues on the projects i worked earlier. Changes to variable in the code was working
you can also not use MonoBehaviour if you dont want automatic seriaization afaik
You'd need to set [Serializable] on your regular class to enable it again
I mean, inspector is just here to show me what's inside the code, the variable, during launchtime.
public class Account : MonoBehaviour
{
public Person person;
public HiddenPerson hiddenPerson;
}
[Serializable]
public class Person
{
public int age;
}
public class HiddenPerson
{
public int hiddenAge;
}
You probably didn't initialize it the 1st time, making it serialized to the type default value (0 here) and modified your code later. If you reset your component, it should go back to 14.
Inspector is not there to show you whats inside the code, not sure if thats even possible to do.
But the easy fix it so set defult values in Awake
I meant, show me what's inside variables.
public class Person
{
public int Age = 14;
private void Awake()
{
Age = 23;
}
}
This behavior has not changed in 15 years of Unity
Not the whole code
But if you want something to show without being serialized, you could consider doing a custom attribute drawer
Oh...
I did...
Maybe that's why..
Use Awake/Start or Init function to setup default values
Na, ActualTime haven't my custom attribute drawer so can't be it..
Yeah i think i'm gonna do that
For debugging purposes use Debug.Log or draw on UI or have secondary variabe visible in the inspector.
I didn't mean the issue could come from a custom attribute drawer, I meant that you could use one for the purpose of readonly data in play mode ^^'
I was debugging already. I'm always doing xD but it wasn't working tho
Why do you need them visible in the inspector?
I thought its for debugging purposes
during development
Unless you are actually using them with prefabs and such
Hey all, I am looking for any information on creating a kinematic character controller. I have started dissecting various repos but am having trouble understanding some of the logic relating to collision detection and translation. Any resources would be greatly appreciated 🙂
Nah, just want to see what variable have insides without having ten thousands log in debug console since i'm doing my code in the Update() function
So i decided to have a ReadOnly attribute drawer. Now it let me see the variables and what's inside
You can show debug.log every 5 seconds too
or w/e you want
also you can collapse logs(not recommended)
You can do that by switching the inspector to debug mode, and you can use trace points (breakpoints that don't halt) to print values in your IDE without adding logs
Oh I havent used inspector debug mode much, what is it good for?
Yeah didn't thought about it tbh.. I wanted to have a space with all my properties changing in real time with the rights titles etc.. easier then having ten debug log hard coded that i'll had to erase or comment later if you know what i men
Oh damn
You shoudnt really have a lot of debug logs all at the same time
I rarely ever log anything, I just use tracepoints
tracepoints?
Alright need to go back to business, thanks for the help
I only really use logs for things that need to be tested in release builds for whatever reason
(but I use Rider, not VS)
oh wow
i have a problem
thats basically a debug log but without extra code 😄
With Rider it even logs to Unity's console now
like here i am lerping player to that transform but it stops in 0.00001 before that
you're not using Lerp correctly
if you want to write the code this way, you should use either Vector3.MoveTowards or Vector3.SmoothDamp
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
VS code
smooth daming is not working giving same result and moveForward is snappy and lerp as well
moveforward worked with time.deltatime
Its fine now thanks
Is there a way to test if a property exists?
I am doing save/load system and if we add new properties I want to test for a property if it exists before I read it
string saveData = File.ReadAllText(filePath);
GameSave gameSave = JsonUtility.FromJson<GameSave>(saveData);
Gold = gameSave.Gold;
In this example, I would like to test if .Gold exists in the save file
read the code of GameSave class
You mean to check if it exist in the save file ?
Save file might not have Gold saved if its from older version of the game etc.
yes
In Js you could do gameSave["Gold"] != null
not sure if its possible here?
i remember json is compatible for this, wont throw exception
Guess I can only test and see :c
oh you mean that Json will return default value
GameSave gameSave = JsonUtility.FromJson<GameSave>(saveData);
Because this will create an instance of a class and then overwrite values from save file
that makes sense if it works this way
So I dont need to do any checks
as long as I read from a class
what do you mean by "test if it exists"? Do you want to know if the json actually has the field in it? Or perhaps if the value is not some default value?
the value (data in disk) wont be overwritten
float cannot be null. it's a struct
Yes that was the idea, to check if the json has a value saved
Not with JsonUtility
other serializers would let you do this, such as newtonsoft, but I don't think it's worth your time
yeah its not 😄
If you need to know this, you're better off with an approach like a separate bool field
I just need to test for default value and do nothing if its default
or a custom "Optional" class that holds the value plus a bool
that makes sense
but if I check for a default value I can just ignore it
if(gameSave.Gold == float.default) continue;
what if the value is legitimately 0 because the user spent all their gold?
the game will load it as 0
in game logic
save load is supposed to apply new values after the game is loaded
oh
its the same
if user spent all gold, it will be 0, but you do make a good point
if we start a game with some gold
maybe load with negative gold
this way anytime gold is negative, you immediately know something is wrong, and can assert it is nonnegative
is there a way to debug and "see"/know what is modifying my player position
i checked all scripts, rigidbodies, animator and colliders, and my player is moving down in a moment were it shouldn't, i cant find what is "making it going down"
i also went in play mode and disabled one-by-one each component and gameobject of my whole scene and the issue was still there
public const int UNASSIGNED_GOLD = -1;
is it dynamic?
start the motion when the audio source’s play gets called
or coroutine to delay them
does the audio file have blank time
and are both audio source and player movement enabled at the same time
have you also looked into PlayDelayed?
i suspect this is an issue with your own script for managing the timing
but you said the audio file has a delay
if the audio file has a delay, how would unity know when audio is supposed to start
"dynamic" what ? the player ?
also after some debug, removing the player rigidbody makes him not moving, so i think the issue is the rigidbody
the thing is, the gravity is disabled, and when disabling my c# script it still goes down
what could make my rigidbody go down ?
if you don’t know what i mean by dynamic rigidbody, you need to look into dynamic vs kinematic vs static rigidbodies before touching unity physics
i feel like the audio file should start with no delay, and delay is added via code, because then you can’t make the delay shorter
also moving objects so music will start at the right time is a very hacky solution
okay so you were talking about my rigidbody, the question was unclear.
yes my rb is dynamic
also i fixed my problem, the issue was some Y velocity staying
still struggling with assembly definitions to get access to scripts in Packages. is there an example of someone defining this?
I tried making an .asmdef which references asmdef and dll from Packages, making an asmdef in my Scripts folder and setting it to reference the packages asmdef above. but idk what I’m doing wrong
Did you put the .dll in the right array ?
what do you mean?
There's Assembly Definition References and assembly references
currently have no assembly reference assets
The dll is supposed to be put in the Assembly References one
in my packages asmdef, i click override references to be able to add some .dll. and that asmdef also contains references to some asmdef files, which I think are in packages
It's the part that handles "external stuff"
oh
let me get this straight. I’m going to just start by deleting all the of asmdef I made to have a blank slate.
I make an assembly reference for externals, and fill it with references to things in my Packages folder. Then I make an asmdef in my own script folder (at root), and set it to reference my newly made external packages reference?
you’re telling me this should work?
You should have something like this
The 1st part is asmdef you define yourself mostly
The second is compiled stuff such as dll
and this is what my script folder asmdef should look like
IIRC this video explains it a little bit https://www.youtube.com/watch?v=k3wHqPZUldw
Ever wonder what that loading bar is actually doing?
Visit:
To join the discord!
00:00 - Introduction
00:12 - Exploring the Unity Project Directory
00:28 - Understanding Script Assemblies
01:16 - Examining Assembly-CSharp.dll
02:00 - Multiple Assembly-CSharp.dll Files
04:08 - Using Assembly Definitions
0...
i have watched several videos, but most of them glance over the external package part
they just drop some asmdefs into their folders, and go “ta dah”
ah
that’s why i’m confused on how to execute
i think i’m a bit confused. this would be one asmdef in my root asset folder, it takes an assembly def reference which is an asmdef in my scripts folder. and as assembly reference I put my Packages .dll?
if you need to refer to a precompiled DLL, put it in Assembly References.
if you need to refer to a DLL that unity is going to generate when it compiles the game, put it in Assembly Definition References
and I do not need an assembly definition reference file to do that?
or maybe I should just make an assembly definition reference file as shorthand for that big list of dlls? Knowing this file isn’t actually needed?
to do what?
Hey there, so in my game you can have different powerups. Some of the powerups grant new abilities like let's say hovering or climbing walls, which other powerups dont have. My question is regarding state machines. Would it be best to make a state machine for each individual powerup or not?
to reference all Package dlls. I mean an assembly def reference can just be a convenient bucket for all the dlls, which other assemblies could reference manually OR just reference my assembly def reference. Is this accurate?
there's a name collision there
An Assembly Definition Reference asset is used to put another folder into an existing Assembly Definition asset
Depends on how you want to implement it, but not one state machine for each powerup
e.g.
I would have a powerup state enum, and potentially one state machine, which lets you know which states you can go to on different triggers
assembly definitions have "Assembly Definition References" -- a list of other assembly definitions -- and "Assembly References" -- a list of precompiled DLLs
Ah, I get what you're asking now. I think that's valid, yes.
If A references a bunch of assemblies, and B references A, then B will see all of those assemblies
like, if you have a powerup SO, it might have have a an enum fields for: Block powerup change to any of these when touching a powerup with the given powerup, Send to this powerup state on take damage. Then specific powerup logic can be handled by individual classes
but I would want to check that
and if I populate this field in asset1 with a ref to asset2, then that makes asset1 depend on asset2?
Hmm okay I see, thanks for the tips 🙂
just for reference, it’s because if you touch one powerup with a “higher” powerup state, you normally block it.
fire mario ignores mushrooms, and turns to super mario when hit, for example.
Yeah
okay, this was wrong.
you must explicitly reference every assembly you use
I created Foo, Bar, and Baz, which were in FooAsm, BarAsm, and BazAsm
BarAsm referenced FooAsm and BazAsm referenced BarAsm
Baz couldn't see the Foo type.
point being, the one big state machine can be made by tacking on logic from each individial powerup SO. or you can put like a power level int system where “if new powerup level > current powerup level, ignore”
that is more restrictive, but depends on what you want to make, since you could follow mario rules, or do whatever
I'll see what works best for me, but I think the enum fields you mentioned are gonna work the best
you could also use a different enum to put powerups into different caragories, and allow interchanging between powerups based on category
I'd do like two sets of enum states if powerups affect movement
This also held true for Assembly References.
(enum to put powerups into different caragories, and allow changing powerup state based on category)
like “helmet type” (shellmet), “mid level” (super shroom), “high level” (fire flower), “override all” (Pballoon)
jumping is already a state, but if you've a powerup that modifies the jump than you need to check a powerup state
Note that, by default, every Assembly Definition asset references every precompiled DLL, so this only matters if you turn on "Override References" and manually choose the ones you want.
he’s already using strategy pattern for custom move logic. he’s asking right now to optimize logic to swap powerups. i think
Yeah I've been using the strategy pattern Loup&Snoop recommended me which works perfect 🙂
ah, guess you can implement ICompare against it all
assumign some powerups have a priority
depends on how mario like he wants it, vs making up his own rules
this is probably a good middleground to give more flexibility than mario, without requiring you to update old files as you add new powerups
which you really want to avoid
Alright thanks for the tips, I'm gonna see what I can do!
good luck
thx!
Anybody has some handy code with them which allows to extend the editor toolbar to make a dropdown (not multiselect) like this. Basically another one besides this
I have this asmdef in my main Assets folder. Packages.External is in a Plugins subfolder of Assets. Files in non-plugin subfolders can no longer see files in my main Packages folder. Why?
specifially, I cannot see attributes in Naughty attributes
References aren’t inherited. I spoke incorrectly when i first answered
See here
woah, that got rid of a bunch of errors
so you're telling me every one of my asmdefs needs to manually call out NaughtyAttributes?
can't I make a reference to automatically include all of my little packages centrally?
You could give it a GUILayout.Height
I feel like there needs to be a more stupid-proof way to do this
because this wouldn't scale to a project with lots of asmdef
What’s the difference between C# and Python?
syntax
as far as I understand, I think assembly definition reference just makes the contents of one folder count as though it is in the folder of the referenced asmdef, as far as assemblies are concerned
everything
…?
i like this answer
it's a simpler question to ask what they have in common
they are both turing-complete programming languages used in modern day.
Tell me some diffences
literally everything is difference, the only common probably is they are programming language (or other one is snake)
Hi everyone... does someone knows how could i resize the right boxhelp in realtime with the left boxhelp? this is the code of both of them https://paste.ofcode.org/8YEY8kfyrSEqxptRJyjQgn. This is the whole code if you need it https://paste.ofcode.org/xT9puUU84FTwjSs4pnBr6G
how do i download files of free unity assets
on the website i dont see a download button
yes but i dont have the files
But like I can write
if (testVariable1 == testVariable2)
{
}
in both languages?
This makes my code work again. Is there a way for me to make a more central collection of references to asmdef of packages I use, without defining them in every single asmdef I make for my own scripts
no. you can't. because their syntax is different. Both have if statements, but you can't just copy paste python code in C# or visa versa. it will not work
because they are different languages
it's like asking what is the difference between spanish and chinese
What exactly do you mean? Should the right box simply expand it's height?
yeah, at the same time the left box does... it is going to be constantly changing it's height...
In your Code, you are using GUILayout.Height for one of the boxes but not for the other one, why not simply use the same height for both?
Another thing you could do is to have a horizontal layout with a given height and make both boxes be a vertical layout with ExpandHeight inside it.
cause i don't want the first one to have always the same height
Yes. That’s what that asset does.
But you haven’t shown us an Assembly Definition Reference asset
see this
As I said, you can use a horizontal layout with the height you want it to have, and then make both boxes a vertical layout that expands their height
lemme try
I haven't made one
I made everything work now, but I think i need a better way to scale it.
putting this asmdef into my root assets folder makes my whole project work. but I want to be able to add asmdefs down below without copy-pasting all those asmdefs every time
Pseudo Example
BeginHorizontal(GUILayout.Height(...));
BeginVertical(GUILayout.ExpandHeight(true));
// Left Content
EndVertical();
BeginVertical(GUILayout.ExpandHeight(true));
// Right Content
EndVertical();
EndHorizontal();
I think it should work even better without specifying a height in the Horizontal layout, but not sure, I'm not in front of my PC rn.
Has been a while since I did Editor Stuff like that, but I remember it being pretty easy to Layout
Hello all. I'm releasing a .unitypackage and it relies on TMP. What's the best practice around that? Should I do, in my package.json, this:
"dependencies": {
"com.unity.textmeshpro": "3.2.0-pre.7"
},
And, even if I do that, I still get that pop-up that tells me to import TMP Essentials, and creates a TextMesh Pro folder under my Assets root folder.
In order to skip this step, can I just ship TextMesh Pro folder within my package? Could that lead into more problems?
I'm not sure, I think you aren't allowed to ship TMP within your package, but you'd be better off reading the TMP and/or AssetStore Licenses.
What's the problem in having the TMP pop-up appear when importing your package? It's pretty common that you have to "install" some dependencies when using external Packages.
Maybe, just to get some insight, you could download some free Asset that has TMP as it's dependency and see how they handled it, or have some kind of "Installer" window for your Package that would import TMP and your Contents with a single button click and without making the pop-up appear
Understood. I just wanted my asset to be easily usable without annoyances but I guess it's okay for that usual window to pop-up. Thanks for your input
You're welcome.
Creating some kind of "Installer" Window would probably be the most user-friendly thing to do 🙂
hi
so i am calling a coroutine function to lerp between 2 positions (only changing the players y), this was all good and smooth
(2) i edited the function so my player is moving forward at the same time, because MovePosition wasn't affecting my player because the transform was overridden by this coroutine (this is my guess)
the code in the coroutine:
float time = 0;
float duration = 0.5f;
float nbLoops = 0f;
Vector3 start = transform.position;
Vector3 goal = new Vector3(transform.position.x, (transform.position.y - 0.5f), transform.position.z);
while (time < duration)
{
transform.position = Vector3.Lerp(start, goal, time / duration) + (new Vector3(1, 0, 0) * Time.deltaTime * _ziplineMoveSpeed) * nbLoops;
time += Time.deltaTime;
nbLoops += 1;
yield return null;
}
this is what i added for (2)
+ (new Vector3(1, 0, 0) * Time.deltaTime * _ziplineMoveSpeed) * nbLoops
why ?
because before doing all of this y lerping, i was doing the following to make the player go forward:
_rigidbody.MovePosition(_rigidbody.position + new Vector3(1, 0, 0) * Time.deltaTime *_ziplineMoveSpeed);
but it wasnt working as said in (2)
the issue is, at some moments while the lerp, my player is like teleporting a bit to forward/backwards, making the lerp not smooth
any suggestions ?
issue gif:
You shouldn't be modifying the transform directly if you've got a Rigidbody on you
If you want to manually set the player's position, you can set _rigidbody.position or _rigidbody.rotation
thx i found it easier to do all the positional animations in code heres how i did the jump if anyone else needs it:
player.position = new Vector3(Mathf.Lerp(initial_pos.x, target_pos.x, interpolation),
** Mathf.Lerp(initial_pos.y, initial_pos.y + jumpHeight, Mathf.SmoothStep(0, 1, Mathf.PingPong(interpolation*2, 1))),** //This is the line that controls y value (jump)
Mathf.Lerp(initial_pos.z, target_pos.z, interpolation));
okay ty
i still have the issue, and its arround the x manipulation
when i change only y i got no issues
waht do you use to record a gif like this
i used obs to record short clip of my problem
screentogif
but this seems easier
Does anyone know how to make the camera background transparent so you can see the desktop and also clickthrough, but also make the ui clickable?
you mean like a trojan?
hello, I have a big problem, I'm making a 2d racing game, I'm with the AI driving, and when it's time to start, the AI goes all the way to the right, I pass the 3 scripts that have to do with the AI, the AIPathWay script, it's the one that creates the line for the AI to follow https://github.com/eduarddo2888/scriptss/blob/main/AIPathWay.cs https://github.com/eduarddo2888/scriptss/blob/main/AICars.cs https://github.com/eduarddo2888/scriptss/blob/main/AIMomevent.cs
You would need to capture the desktop and draw it in your game.
i already did it
no
A hand an hour ago I'm asking for help please guys
Probuilder question - I'm having some troubles with UV editing, specifically being unable to move vertices, and scaling seeming to be centered on the origin (I think?) - video attached. Am I missing something??
Ask in #🛠️┃probuilder
Ah thanks
hi, pls
the AI instead of following the route, which the route has its own script, the AI car ignores it and only rotates in circles in the center of the map
you’ll get better turnout if you ask a very specific question rather than throwing out 3 scripts hoping someone to find a problem in one
hi, I have a big problem, I'm making a 2D racing game, I'm with the AI driving, and when it's time to start, the AI goes all the way to the right, circles towards the coordinates of the folders where they have all the waypoints, instead of following the waypoints that are marked, I pass the 3 scripts that have to do with AI, the AIPathWay script, is the one that creates the line for the AI to follow https://github.com/eduarddo2888/scriptss/blob/main/AIPathWay.cs https://github.com/eduarddo2888/scriptss/blob/main/AICars.cs https://github.com/eduarddo2888/scriptss/blob/main/AIMomevent.cs
Hi guys. Can someone help me with these errors? I want to build APK
Okay
I really need help, I don't know what to do anymore to get some attention
the problem is you basically dumped a huge amount of code and just said "the ai goes to the right". You need to do some of your own debugging and get to the root of your issue. Nobody is going to dive into all that code and try to understand it.
Also after waiting a total of 10 minutes and asking for attention is a sure fire way of not getting any attention
perhaps #854851968446365696 should be consulted here
nah, over entitlement problem 101
What happens to Debug calls in build?
Does the engine actually call shit or does it know to just do nothing?
Like if I construct a string and throw that into a Debug.Log, the string construction definitely still happens regardless.
Right?
Debug.Log still prints in a build, it just prints to the player log
but if you go and manually change the setting that makes it work in builds, then yes the string is still constructed. the method just doesn't do anything with it afaik
in development build , they are written to player.log
Yes, one option is something stupid and annoying like:
#if DEVELOPMENT_BUILD
Debug.Log("Hi " + i);
#endif```
if you care enough
Hmmm. Is it recommended to clean up logs before releasing a build? I imagine they do cause minor performance losses.
Another is to use the [Conditional] attribute
Tell us more!
better yet, implement your own conditional debug.log
Make a wrapper function with the Conditional attribute applied and call that instead
I feel like abstracting unity debugs into your own logger class is good practice.
absolutely
I always have a build tool that sets the stack trace level for builds and resets it afterwards
(it is awful it's the same setting as the console window)
Because the stack trace is a major part of the logs' cost
Would you wrap that in something like a ScriptableObject?
And just toss it to who needs it?
(and size)
no, a static class
Then you can only have 1 logger 🤔
why would you need more than 1 ?
Idk, maybe you want ones for different domains.
Logger for UI elements, game entities, managers etc.
Just have an atypical singleton then, and allow construction of instances
this is what I use in all of my systems
public class ErrMsg
{
public static bool Trace = true;
public static void Log(string msg, bool force = false)
{
if (Trace || force)
#if (UNITY)
Debug.Log(msg);
#else
Console.WriteLine(msg);
#endif
}
}
Also note, if you just use tracepoints instead of logs for debugging then you have a whole lot less to do if you want to clean up. Personally I keep logs in builds, just don't have stack traces on for info level.
Logs are where I get info about what lead up to an error in release builds
If I want to find something out in detail in another kind of build, the debugger can do that
Most of the point of a domain-specific logger is to add prefixes and formatted state
You could make a static log and extend it to whatever classes you need it in, for example:
public static class GameLog
{
public static Log(this Behaviour obj, string context)
{
Debug.Log($"{nameof(obj)}: {context}");
}
}
public class SomeScript : Mono
{
void SomeFunc() {GameLog.Log("hi");} //outputs "SomeScript: hi"
}
You could also make a dictionary of the types if you really wanted to have different log files for different types though imo that may be overkill unless your doing very specific debugging
so i just used linux to install unity on my chromebook. believe it or not it actually works but im getting a bunch of error codes all about events, did i forget to install something?
You need to post the error messages along with your original message to get help faster, next time
TLDR Chromebooks are a huge pain to deal with, best to stick with a cheap pc that ran windows
Everything I've found states that ChromeOS will always run alongside your linux OS. Haven't found anything saying you can actually flash the whole computer to only run linux
Found one guy who supposedly did it: https://superuser.com/questions/662927/is-there-a-way-to-completely-delete-chrome-os-on-a-chromebook-and-install-linu
If you've toyed around with rooting an android, you might see some similarities and have the same reservations when it comes to following a guide--likely your device is different enough that those steps are not relevant
I applied for a job and they sent me a unity project to code
They supplied an API (Below) and told me to complete the game of tic tac toe.
I was unfortunately rejected, they said that my code architecture needed more work and that it could have been more abstract
I am kind of confused on what they mean and was hoping someone could look through my code and let me know what can be improved in the architecture or in general
UserActionEvents
- UserActionEvents_TileClicked
- UserActionEvents_StartGameClicked
- UserActionEvents_LoadStateClicked
- UserActionEvents_SaveStateClicked
GameView
- ChangeTurn
- StartGame
- SetTileSign
- GameWon
- GameTie
- ChangeTurn
- StartGame
https://pastebin.com/raw/hvBVSLBt
I also wrote GameStateModel which is a class with properties so that I could serialize and deserialize specific variables in my class, i didnt include it because I didnt think it was important. if it is ill include it.
I don't know what people expect from a game like tic tac toe lol
me neither I was caught off guard when they said the code needed improvement in its architecture I really thought I did a great job
is there a way to make my project tab show all .asset files tied to a specific SO class?
mostly interviewers who have zero coding knowledge and are going back a sheet of paper looking for buzzwords
synnergistic assemblies
team-oriented githubs
My biggest weakness is dealing with Burst Intrinsics
alright ill take what they said with a big grain of salt and just move on >.<
Also transformice was a great game, your pfp really sparked some memories LOL
and thanks ofc 🙂
looks fine to me honestly /shrug
My old boss once asked me to deal with an extremely complicated Dynamically Allocated Array. It took me a few days, but I eventually came back to him with a complete implementation of a Doubly Linked List of Structs.
And everyone clapped
They probably just wanted you to have a middleman class that calls an interface that defines those methods
UserActionEvents_TileClicked
UserActionEvents_StartGameClicked
UserActionEvents_LoadStateClicked
UserActionEvents_SaveStateClicked
and then have your GameBoardLogic class implement that interface (which it does anyways...but just doesn't derive from an interface)
congrats bro
I was just mocking these interviewers @dawn nebula
I know. A doubly linked list of structs is basic af and also kind of a shit structure anyway.
"Dynamically Allocated Array"
so... an arraylist? lol
just wait until I hit him with the unsigned longs
I always wondered why LinkedLists were featured so prominently in early programming education.
worst ones are those asking you to do some specific binary trees or some recursive stuff
if you mean you want to see all of the asset instances of your SO you can use t: to search by type
Considering they're pretty awful.
and im like let me just google real quick
where is the best place to post a specific unity question here?
!support
Take a look at #🔎┃find-a-channel
:warning: This is not a channel for official support.
Please do not ping admins, moderators, or staff with Unity issues.
ty
does this mean no questions? :p just trying to follow the rules
if it's very specific to the editor you can consder #💻┃unity-talk
ok thank u
Did you read what it says at the very top of #🔎┃find-a-channel ?
oooo baybee
I would be doing tic tac toe with bitmasks, but there's nothing wrong with the above approach 😄
ok i asked there! thank you friend
Thank you again for your input guys 🙂
You have the appriciation of some random person on the internet now
what like a 2D array of bits and each move masks the coordinate?
can somoene here help me with my open gl code?
unless it's specifically using Unity's Mesh library