#archived-code-general
1 messages · Page 256 of 1
but you can maybe profile it? i never tried
ultimately it will always take some time though and if there's no reason to spend that time, it seems good not to
the more stuff there is, the longer it takes
i do need to look into profiling that
It's ultra-fast in an empty project
does domain reload also have to reset non-serialized fields in SOs?
i don't think it touches SOs
mmm, that's something I'd need to double check
I know that changes to serialized fields on scriptable objects can appear to persist from play mode session to play mode session
(and then go away after the objects actually unload)
right? i think that's because domain reloads are just for monobehaviors
which is why statics are a problem, because they too get 'missed'
a domain reload will reset static fields back to their default values
it's creating a new application domain
afaik
time to go check
!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.
haha yeah i'm starting to doubt everything now >_>
why does the enemy stay in place? https://gdl.space/xigebuluzu.cpp
yet still tries to move towards me like i want it to
ok, this isn't quite right
objBase.customDrawLogic = gameObject.AddComponent(objBase.drawSpecialLogic.Type) as ICustomDrawLogic;
}
Debug.Assert(objBase.customDrawLogic.gameObject == gameObject, $"Cust....```
objBase is an SO. customDrawLogic is a public, non-serialized interface field. That interface contains a singleton. This code (at the last line) says missing reference exception because objBase.customDrawLogic references an object that has been destroyed
I'm literally checking if it is null in the line above
sweet, exactly what I expected
the Domain Reload reset the non-serialized fields
but Unity persisted changes to the serialized fields
that is dogshit
I'm just turning back on domain reload
I need to domain reload anyway whenever I change my code
and he most common case is entering playmode exactly once after changing code
I am absolutely not going through every non-serialized field, and micromanaging that
and then depending on having done that right
nvm i figured it out
So you've checked if it was null above. Assuming it was, you've attempted to add a component to this game object and reference it as an interface (potential null).
it does implement that interface tho
the cast can silently fail if something is wrong there
it works fine on domain reload
oh, I see it
What if the added component isn't of the type?
customDrawLogic is an interface type
you aren't getting Unity's null comparison logic
Relative to cast
you'd need to cast it to UnityEngine.Object and then check if that's null
the interface type is just going to do a reference equality check
I used Debug.Log right before my assertion, and it is not null
and that returns false because it's not literally a null reference
it's just a reference to an object unity happens to think is destroyed
Else we're assuming it isn't entering the if statement and actually null but not null
but it does throw a missing reference exception the moment I call customDrawLogic.gameObject
this is the issue. you don't need to keep looking :p
and I checked customDrawLogic == null AND customDrawLogic is null. Both are false
Maybe log if the expression evaluated is null or if the if-statement is occurring
Or if the component after cast is null
without a domain reload, all of these old static references will remain exactly as they were in the last play session
I'm assuming the adding of the component is valid
they will be references to objects that Unity considers destroyed
but they will still be there, regardless, because C# doesn't care what Unity thinks
this is happening specifically because of the interface type. it skips Unity's custom null comparison logic.
If the domain is reloaded before you enter play mode, that field will be a literal null reference
honestly, I think I will spend less time waiting for domain reloads, then I will debugging to make sure not domain reloading is an accurate match in final build
it's especially important to disentangle unity objects and C# objects from each other when you're dealing with interface types
I have this Input Actions Asset.
What I want to achieve is : Change the value of the 'Movement' Action through CODE at runtime
I know you can read values by getting the action, and doing ReadValue
However I want to know how to SETValue (which doesn't exist) to manually override this at runtime
lets Say I want to temporarily control the input through code
how do I do this?
I would not do that
I would make a singleton with a super high execution order. Have this subscribe to Movement, make whatever edits you need for its own internals, and then all your scripts reference this singleton
eg ProcessedInputManager : Singleton<ProcessedInputManager>
dang. okay.
Would've been nice to have the option for everything to go through a single action. That way the player can switch between using the premade bindings (WASD) and the virtual controls im making
and it would've been a cleaner implementation i feel
but if its not ideal or doable, I guess I will have to work around it.
I wonder if https://docs.unity3d.com/Packages/com.unity.inputsystem@1.7/manual/Testing.html could help you out
you wouldn't actually be writing tests, so you'd be able to ignore most of it
you'd be creating a fake device, basically
Hey guys. Currently i have a variable that is true when spacebar is held (using new input system). This works fine for what i have, but now i need this variable to be false after like a 0.x delay. So it should only turn true for a while after a press/hold. Any suggestions or solutions on how to approach this problem?
My issue here is that when the button is held, it is always true as it is subscribed to jump.performed
The input system alone won't do that for you. Maybe you could write a custom processor?
I would just implement that logic myself.
The First Person Controller from the Unity Starter Assets limits the number of decimal places to 3 after calculating speed. Is this an optimization of some kind? FirstPersonController.cs, line 179.
The comments don't offer an explanation, and I haven't found a reference to this as a general technique on Google...
Most people dont just have the code open/wont go find it to help you. Can you show the lines you're referring to?
Sure thing: https://pastebin.com/7kaJPELb
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
taking an online tutorial and I ran into a situation where the instructor's implementation smells, however I'm not an expert in unity/C# so I'm assuming there is a reason he went with the implementation that he chose. Here is his top-level scriptable object. He's assigning bools to indicate the "type" of room that it is. This seems bad because:
- it's not really a type-safe way to assign behavior to something (you're checking a property at run-time instead of type-checking it during compile, when you're validating things)
- each room type is now aware of the other characteristics of room types outside of itself
[CreateAssetMenu(fileName = "RoomNodeType_", menuName = "Scriptable Objects/Dungeon/Room Node Type")]
public class RoomNodeTypeSO : ScriptableObject
{
public string roomNodeTypeName;
#region Header
[Header("Only flag the RoomNodeTypes that should be visible in the editor")]
#endregion Header
public bool displayInNodeGraphEditor = true; // for example, we don't need Entrance in the dropdown - since it's a special case
#region Header
[Header("One type should be a corridor")]
#endregion Header
public bool isCorridor;
#region Header
[Header("One type should be a corridorNS")]
#endregion Header
public bool isCorridorNS;
#region Header
[Header("One type should be a corridorEW")]
#endregion Header
public bool isCorridorEW;
#region Header
[Header("One type should be an entrace")]
#endregion Header
public bool isEntrance;
#region Header
[Header("One type should be a boss room")]
#endregion Header
public bool isBossRoom;
#region Header
[Header("One type should be None (Unassigned)")]
#endregion Header
public bool isNone;
}
Is there any reason that I shouldn't refactor it into something like this:
public class Corridor : RoomNodeTypeSO
{
roomNodeTypeName = "Corridor";
}
public class CorridorNS : RoomNodeTypeSO
{
roomNodeTypeName = "CorridorNS";
}
...
...
...
basically, wherever he would validate the room type via some check like isCorrider - I could check that it is type Corridor.
is there some pattern in C# that makes it useful to set this kind of behavior up via these OOP properties/bools?
It's hard to say what they were thinking, I'm gonna assume it's for consistency sake like for printing the speed to screen. Even the other code is questionable
this could just be an enum
Yea enum as Fen wrote, but dear lord those regions are horrible
using many bools would make sense if a RoomNodeTypeSO could be many types at once
and yes, I have no idea what's up the regions
can enums have the stringy-name thing on them?
they aren't exactly saving space...
enums are just integers under the hood
but you can get the name of an enum and display that, or write a method that gives you a string name for an enum
i mean it seems like he's going to use the roomTypeName string for labels later
i see
public string GetName(EnumType myEnum) => myEnum switch {
EnumType.Foo => "Foo",
EnumType.Bar => "Big Bar"
};
not sure about the behavior later, but i think it may need more functionality than enum?
like an algebraic datatype
a "family" of coproducts to a parent type
i just hate the bool thing and I'm not sure if it's going to be important later
Alright, thank you for taking a look at it
I would give a room a list of qualities it has
like having an exit in the east, or being a boss room
but that's getting into "how your game is designed" territory
When i shoot into the void, the hitposition becomes 0,0,0. How can i make it so it chooses a point within the path instead of the origin
I would not create a custom type for every possible kind of room
RoomWithEastExitAndABoss
Even the lerp in the code is kinda bad, so you're better off finding a new guide/tutorial. That was likely written just to get something working, rather than being a production ready script
I wouldn't use the type system to make sure I create valid room layouts.
why not?
you could express individual attributes as interfaces, I guess
that sounds incredibly funky
!code and also you need to check if the ray hit anything. If it didnt, then choose a point along the ray (like 50 units away for example)
📃 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.
for instance, a function that's like ConnectingToRoomNode (SomeKindOfCorridor corridor) would tell me at compile-time that i need to be using a corridor
whereas the isCorridor thing allows you to pass any type of room
how would i write that?
like the SOLID principles
I have a couple different systems I'll be trying. That was about the feeling I got from the code as well... Good to know it wasn't just me! Thanks again
You already check if the ray hit anything, just dont use the hit.position if it doesnt hit anything. It is 0 because it didnt hit anything
if you really can only connect to corridors, then sure, but what if you want to connect to other rooms directly?
now you need to prove that the room can be connected to
lol I'm actually not sure yet!
im guessing that's a later lesson
what if it doesn't have a door that can connect to your room? maybe it's already attached to something else
how would i write it to to choose a position along the ray?
at some point you wind up trying to punt the entire runtime program into the compiler
and that takes you to c++ template hell
yeah this is what i like!
There is a method under Ray which does this for you, look at the docs. I dont remember the name right now
oh cool thanks
A Ray provides a origin and direction, you can use the direction and multiply it by however far you want it to travel, the resulting vector would then be your end point, or the equivalent to a "hit point"
transform.Rotate(Vector3.up * mouseX);
anyone have any idea why camera is snapping so weirdly?
Hi everyone. I try to keep this short. I always loved game dev and decided to try and learn unity with C#. For now only 2 D tho. I heard from someone that there is a tutorial for Flappy Bird, which is about one hour long. I am enjoying the process of following it and Start to understand the basic basics. But I don’t know what I am suppose to do after. Just create a Game and learn what I need when I need it, learn advanced C# or focus on thinks like sprite art and game design while getting code from ChatGPT or so.
i bet you included Time.deltaTime when calculating mouseX
if you did, that's wrong. remove it and adjust your sensitivity down to compensate
removed now but still seems to be snapping
show your whole script
void UpdateLook()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity;
transform.Rotate(Vector3.up * mouseX);
float xRotation = cam.transform.localRotation.eulerAngles.x;
xRotation -= mouseY;
// clamping
if (xRotation > 180)
{
xRotation -= 360;
}
xRotation = Mathf.Clamp(xRotation, -90, 90);
cam.transform.localRotation = Quaternion.Euler(xRotation, 0, 0);
GetComponent<Rigidbody>().angularVelocity = Vector3.zero;
}```
I tried adding camera smoothing but still snapping but smoother
you've got a rigidbody
that's going to be fighting with your attempts to rotate the transform
ah, that's on a different object?
ok, you're rotating transform with the yaw input and cam.transform with the pitch input
Get rid of the rigidbody and observe how it behaves. It should look smooth at that point.
ok one second
I haven't made a 3D character with a rigidbody like that before -- always a character controller of some kind
What you could do is rotate the camera to where you should be facing every frame in LateUpdate
i tried using charactercontroller but it seems to break physics
especially if you also have a Rigidbody!
you'll want to track the yaw angle you want to have, instead of using Rotate to spin the transform a little bit each frame
Set the rigidbody to have that rotation in FixedUpdate and make the camera have that rotation in LateUpdate
okay give me a second
ok I made x axis and for now it looks promising
still behaves weird
maybe it's unity's editor problem and on compiled game it will work correctly?
Have you checked how it behaves without a rigidbody?
Ah. That's why I asked for the whole script :p
Each frame, a certain amount of mouse input is detected
since you were using FixedUpdate, you were only getting whatever input happened to come in the frame before a physics update happened
sorry for problem and thanks for help
FixedUpdate is also bad for Down/Up input, since those are only true for a single frame
and you can wind up missing them
I know but I remember doing some physics tests back in the day
and it was really weird when using Update
Physics-related things should happen in FixedUpdate, yes
If you have a BehaviourTree and a GOAP system for your AI Agent, do you only communicate between BT and GOAP
or do you also communicate with BT and Agent as well?
Goal: Reach Player or Move To Position
but there are other things such as attack which is just one sequence of a task therefore is it worth going through the GOAP class to do this?
I used those Quaternion (eulerAngles) and Transform (localRotation) methods, until Quaternion.Euler, but they gave the same result (the same as in the screenshot). But even though one believes that it affects the rotation somewhat, it seems that it still moves correctly even if the values are not coincident (I no longer know if those values affect in terms of precision).
Yes, you'll get a tiny bit of numerical error
Hello devs, who knows how to get this Vector3 coordinates , knowing
- StartPoint(Vector3),
- Distance from startPoint , and
- Angle (Vector3)- it is Direction vector.
For example if i write this Raycast, it - will end exactly at point i need.
Physics.Raycast(StartPoint, Angle, out hit, Distance );
but i just need that end point's Vector3
What, get the point where a raycast hits something? its hit.point no?
no i dont need to check anything, i dont need collision check. only Vector3
Cant you just use the hit.position? Also Ray has a method which calculates the position after a distance. It is a simple calculation still of originalPos + (dir * dist)
or if nothing is hit, it's literally just StartPoint + (Angle * Distance)
assuming Angle is normalized since you said it was a direction vector
at moment i'm using that "Angle" in Physics.Raycast
so i assume it is normalized
dunno what you mean by that
Hey guys, I imported google ads package and when it is resolving for android I get this error:
Gradle failed to fetch dependencies.
Failed to run 'C:\Users\Sebas\Documents\Unity Projects\Juego de los aviones - copia\Temp\PlayServicesResolverGradle\gradlew.bat --no-daemon -b "C:\Users\Sebas\Documents\Unity Projects\Juego de los aviones - copia\Temp\PlayServicesResolverGradle\PlayServicesResolver.scripts.download_artifacts.gradle" "-PANDROID_HOME=C:\Program Files\Unity\Hub\Editor\2021.3.29f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK" "-PTARGET_DIR=C:\Users\Sebas\Documents\Unity Projects\Juego de los aviones - copia\Assets\Plugins\Android" "-PMAVEN_REPOS=https://maven.google.com/" "-PPACKAGES_TO_COPY=com.google.android.gms:play-services-ads:22.5.0;com.google.android.ump:user-messaging-platform:2.1.0" "-PUSE_JETIFIER=1" "-PDATA_BINDING_VERSION=4.0.1"'
stdout:
ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation.
stderr:
exit code: 1
I searched for solutions online and people said I should add JAVA_HOME to my environment variables, I did it but it still throws same error
can a dictionary have a null key?
like actually having a value defined for the key “null”
no
impossible to generate a hash value for null
that’s what I was thinking, especially in case of keys being value type
Hi, i have a problem with my cameras, and it may be something dumb but here it is. I am trying to use a secondary camera to create a reflection of the upper part of my screen in a river, and even when i change the settings of the second camera to be the exact same size as the main one, it isn't. Here are the screenshots
they have the same size/scale parameters but are still different sizes i don't understand why
It kinda looks like they have different positions in the scene view
Oh, they do
I think it's just the difference between screen resolutions.🤔
They seem to be roughly the same size on the y axis. Only different on the x axis.
And your scene view window on the top screenshot seems to be slightly wider than on the bottom.
okay thanks for the tips vOlt i will try it out right now 👍
Can I have a question about how many design pattern does I need for a pokemon type game ?
How many pushups do I need to do to order pizza?
Does that make any sense? Neither does your question.
You use whatever design patterns make sense in your project. The count doesn't really tell anything. And the type of a game is not related to design patterns in any way either.
0-1 at minimum. 0 will be tough though
Does anyone know how you would script the equivalent of a fixed joint? I know they essentially just add the exact amount of force of the object they are attached to, but idk how the rotation would be done. (I can’t use a fixed joint because I need the object to be able to move both with and independently of the second object at the same time. I found an old thread detailing pretty much my exact problem but with no answers: https://forum.unity.com/threads/script-the-equivalent-of-parenting-for-physics.393490/ . Any help would be appreciated!
maybe https://docs.unity3d.com/Manual/class-PositionConstraint.html and/or some rotation constraints, which let you kind of do 'parenting' without the hierarchy? there's also damped transforms in the rigging package which feels similar to but not quite what you need https://docs.unity3d.com/Packages/com.unity.animation.rigging@1.1/manual/constraints/DampedTransform.html
otherwise yeah you can write a script which will copy whatever pieces of that over you need, it's just figuring out exactly what that means for what you're doing
I would insert my own custom system that runs after FixedUpdate and just copy over the velocity and angular velocity from one rb to the other. https://docs.unity3d.com/ScriptReference/LowLevel.PlayerLoop.html This repo has helper methods to make things easier https://github.com/Baste-RainGames/PlayerLoopInterface
I'm trying to figure out what refresh rates are supported as I'd like to include the monitor refresh rate as an option when running in fullscreen mode. I wrote some code to get all refresh rates and screen res options as reported by Screen.resolutions.
My confusion is that it is reporting some strange refresh rates that I don't understand where they are coming from.
My code displays the following as refresh rates, but Nvidia / Windows only report 60hz and 120hz as supported by my monitor.
60hz
72hz
75hz
120hz
56hz
70hz
Code I'm using:
void GetSupportedScreenSettings()
{
//Temp lists to add objects to as we collect possible options
List<int> tempRefreshRates = new List<int>();
List<Rect> tempScreenRes = new List<Rect>();
foreach(var res in Screen.resolutions)
{
//Use a rect cause whatever, I just want a simple object to store width/height
tempScreenRes.Add(new Rect(0,0,res.width, res.height));
tempRefreshRates.Add(res.refreshRate);
}
//Move them to a distinct array
supportedScreenRefreshRate = tempRefreshRates.Distinct().ToArray();
supportedScreenResolutions = tempScreenRes.Distinct().ToArray();
string temp = "";
string temp2 = "";
foreach(var i in supportedScreenRefreshRate)
{
temp += $"{i}hz\n";
}
foreach(var i in supportedScreenResolutions)
{
temp += $"{i.width}x{i.height}\n";
}
Debug.LogError(temp + "\n" + temp2);
}
Is it possible to configure a script to build in one batch 3 different versions for the same platform (webgl)?
My 3 cases are:
-Linear colorspace and DXT texture compression
-Linear colorspace and ATSC texture compression
-Gamma colorspace and ATSC texture compression
Hi, i have a problem with Nav Mesh. If I create more than 1 enemy, they go to the corners and stand there
if you leave the enemy alone then everything is fine
What is best for this thing? I have a grid that is manually built (not built on start). Each tile can have some differences. Using InputSystem, If i press wasd or gamecube dpad I can navigate the grid (a grid cursor should appear over the tile). Only with mouse if hover a tile the grid cursor automatically goes there: tile layermask.
I could use IPointer interfaces or else a mouse to screen raycast but I don't know how I would get the specific tile since all are adjacent
Sometimes I struggle to find the better approaches
actually most of the time
hey, does anyone have idea why there is this huge input lag? when I release key my character is still going
I found that axes Horizontal and Vertical are interpolated for keyboard, can I disable that?
I want it to be normalized 0 or 1, not 0-1
Use GetAxisRaw rather than GetAxis
thanks!
No problem
works exactly like i wanted thanks again
Hey so architectural question here. I have a series of items that the player can collect. Once collected, the item shouldn't appear again. How should I go about tracking this? Obviously each item needs an ID. Should I have some ScriptableObject representation of the item data that contains the ID, prefab and any other relevant data?
any idea why night is so bright?
RenderSettings.ambientIntensity = 0;
sunLight.color = Color.black;
sunLight.shadowStrength = 1;
Can anybody suggest why the animation trigger twice?
You probably aren't setting isPunchR to false early enough
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Camera : MonoBehaviour
{
private GameObject Player;
private CarController RR;
private GameObject child;
private GameObject cameralookAt;
[Header("Parameters")]
public float speed = 23;
public float defaultFOV = 0, desiredFOV = 0;
[Range(0,2)]public float smoothTime = 0;
private void Awake()
{
Player = GameObject.FindGameObjectWithTag("Player");
child = Player.transform.Find("CameraPOS").gameObject;
cameralookAt = Player.transform.Find("cameraLookAt").gameObject;
RR = Player.GetComponent<CarController>();
defaultFOV = UnityEngine.Camera.main.fieldOfView;
}
private void FixedUpdate()
{
Follow();
boostFOV();
}
private void Follow()
{
if (speed <= 23)
speed = Mathf.Lerp(speed, RR.KpH / 5, Time.deltaTime);
else
speed = 23;
gameObject.transform.position = Vector3.Lerp(transform.position, child.transform.position, Time.deltaTime * speed);
gameObject.transform.LookAt(cameralookAt.gameObject.transform.position);
}
private void boostFOV()
{
if (Input.GetKey(KeyCode.LeftShift))
{
UnityEngine.Camera.main.fieldOfView = Mathf.Lerp(UnityEngine.Camera.main.fieldOfView, desiredFOV, Time.deltaTime * smoothTime);
}
else
UnityEngine.Camera.main.fieldOfView = Mathf.Lerp(UnityEngine.Camera.main.fieldOfView, defaultFOV, Time.deltaTime* smoothTime);
}
}
I want to know why the camera follows the car for the first second but then it slows down continously to the point where it doesnt move
because you're using the current FOV in your Lerp
Hi, I am having this weird problem.
I use the AssetDatabase class witch it linked the package for. But it keeps unlinking and every time I connect it again by clicking the option given in the error message it's fine for some time (from 10s - 2min) and then does it again.
Do you know what might cause this? I am using it in the Start() method.
AssetDatabase is a UnityEditor class.
You can't use it in the built game.
What are you trying to achieve here?
(that's not necessarily what's causing the error message here; it's just important :p )
I have a basic movement and a basic camera script on my unity project i've notice this problem where the camera is "jittery" it is very noticeable if you look around an object
heres my camera script:
public float sensitivity;
public Transform playerCam;
private float xRot;
private Vector2 playerMouseMovement;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
void Update()
{
playerMouseMovement = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
xRot -= playerMouseMovement.y * sensitivity;
transform.Rotate(0f, playerMouseMovement.x * sensitivity, 0f);
playerCam.transform.localRotation = Quaternion.Euler(xRot, 0f, 0f);
xRot = Mathf.Clamp(xRot, -90f, 90f);
}
I am trying to get a path of a file which is part of the script
I assign the file from directory where it's saved
the file contains string which I'll be saving to an Array
I could put the path in manually but I want to use it for more files later and writing path manually just seams weird
I was about to say "don't use deltaTime!"...but you aren't! good
How is the player being moved?
These files won't exist in the built game.
all of your Assets get bundled into a few big archive files
What are you trying to accomplish here?
not "get the path of a file"
sorry, I don't think I quite follow
Hey could anyone help me create a good script for movement wasd on unity i have no clue what im writing and need help really bad
rigidbody i can send the code if you want
What are you doing with these files? Why do you think you need file paths?
for some reason the player is unable to move forward even though its detecting the fact that the player is pressing the W key . i am using ;netcode for gameobjects; for the networking
is the camera parented to the object with the rigidbody?
the rigidbdy will, by default, only move during physics updates
this will result in a lot of jitter
open the file
store the content of the file into Array
and then use and modify the Array
yup
If you just need to read a text file, then you can directly reference a TextAsset
that's the kind of asset you get when you drag a .txt into your project
ok i will try updating the camera's transform to an empty gameobject while keeping the player outside/unparented to the player
turning on interpolation on the rigidbody could help
I'm not sure what the "correct" fix is here, though. I've never really done rigidbody-based first person games
ok the code seems to work now
AssetDatabase doesn't exist at all in the built game, and the files in your Assets folder will also not exist in the built game.
oh okey
sry I haven't realised that it comes with this kind of method
thank you so much for your help
okay, I think I get it now
thank you
i already have the rigidbody set to interpolation
ok so i tried doing that but now i cant look on the x axis
its only on the y axis
In that case, make sure that you are not modifying the transform of the rigidbody at all
it'll overwrite whatever you do
how do you make it so that the forward velocity is capped after it reaches a certain value ?
compare and set?
Clamp it
also is there anyway to check if the forward velocity reaches a certain value ?
if ?
oh wait does velicity use local or global posititions ?
neither
what? Velocity is not positions
sorry for the confusion . i am applying a relative force on the Z axis and what i want to do is to see if that forward velocity is more than my max speed and if it is cap it to that value
hopefully this makes what i am trying to do a bit clearer
so check if velocity.z is greater than max speed and if so clamp it to max speed
so it would look like this right ?
no
hey how can i make crouch code for my movement code
Velocity will be represented in world space, use transform.InverseTransformDirection(rb.velocity) to convert it to local space
Or multiply the velocity with your transform.rotation, that should do the same normally
so it would look like this ?
Look at the docs for Clamp, what you wrote doesnt make sense.
Also I believe force isnt added right away, so you might want to clamp the velocity regardless if they press W. Or you might run into cases where people can move faster than your max speed because they let go of W and it didnt clamp properly after the last add force
allright . thanks for the help
I need to access the data from tiles but it say to me there is an error, I don't understand what is the error
why would you think that the TileData struct contains a property tiles?
https://docs.unity3d.com/ScriptReference/Tilemaps.TileData.html
it's in a scriptable object
and?
Side-step, avoid using var when the type on the other side is not clearly apparent
This makes the code harder to read
Show the definition of TileData, because seeing how it's colored, it's a class, meaning it's not Unity's TileData struct
yep it's a script
one whole tile
Rename to tile for clarity
let's say I have an Action<>, and I want to subscribe a method to it as Method(fixedInput). I want to also be able to both += and -=, and I worry doing
+= () => Method(fixedInput);
will make that not work because it is anonymous
suggestions for how to do this the most cleanly?
I could define a private method, but just wondering if that is the only way
also, if you must duplicate Unity class/struct names at least have the sense to put them in your own namespace
Youd have to store the delegate or write it in a method to be able to unsubscribe. Unless you want to unsubscribe by assigning the whole action to null
You can store the lambda in a field, then (un)subscribe to/from the field
I have a system like this which is a lot smarter
Good. Now you don't need the inner foreach loop, add tileData.tile to your Dictionary
ok thanks
where can I ask about meshcollider?
tiles is not an IEnumerable
in my equivalent of a tiledata class, I have a method that outputs a List<TileBase> to get all tiles for that tileData.
this way I can have a TileData that corresponds to multiple tiles
I have a child class of it, which does have multiple tiles
TileAssembly : TileData
also, don't do public float etc in your SOs. you want to protect that shit like a dragon protects their hoard of gold
the standard pattern is:
[field: SerializeField] public float myValue {get; private set;}
if you make it fully public, you allow other scripts to not just read, but to EDIT your SO, which would be catastrophic for this sort of system
do you understand?
yes i do
one thing I wish I did was make that dictionary a private dictionary, with public property IReadOnlyDictionary
private Dictionary<....> myDict;
public IReadOnlyDictionary<....> MyDict => myDict;
this makes the dictionary publicly readable, but nothing is allowed to modify it outside the class
because I use this dictionary literally everywhere in my game
Hey all,
I have an object with AudioSource and a controller script (UIAudio) attached to it, and I want to play different sound effects. But now that I want to play coin sfx, it still plays the main click sfx, even if I manually change the clip to coin sfx from unity inspector.
public class UIAudio : MonoBehaviour
{
[SerializeField]
private AudioSource audioSource;
[SerializeField]
private AudioClip clickAudioClip;
[SerializeField]
private AudioClip coinAudioClip;
private bool shouldDestroy = false;
private void FixedUpdate()
{
if (!audioSource.isPlaying && shouldDestroy) Destroy(gameObject);
}
public void Play(bool shouldDestroy)
{
audioSource.Stop();
audioSource.clip = clickAudioClip;
audioSource.Play();
// I believe below is to continue playing the sound effect in the next scene, and then delete the object.
this.shouldDestroy = shouldDestroy;
DontDestroyOnLoad(gameObject);
}
public void PlayCoin()
{
audioSource.Stop();
audioSource.clip = coinAudioClip;
audioSource.Play();
}
}
uIAudio.PlayCoin();
which method
how do you call playcoin
Is it important? I believe it definitely gets called, as I logged it and it also plays the other sound effect. (click clip)
its kind of important if you want to debug it
public void WatchAd()
{
//uIAudio.Play(false);
if (IsLoading()) return;
BeginLoading();
RequestAd();
#if UNITY_EDITOR
EndLoading();
EarnNClose();
#endif
}
private void EarnNClose()
{
uIAudio.PlayCoin();
coinManager.ReceiveMoney(14);
ClosePanel();
}
here. WatchAd() method is part of another gameObject and gets called by a UI Button
and these two run for sure ?
EndLoading();
EarnNClose();
Yeah, I just put a Debug.Log in PlayCoin itself to make sure it gets called
oh ok hmmmm . that DDOL is kinda weird but shouldn't cause issue if you already start with correct assigned sfx
can someone explain why my IDE is putting this global:: thing on some class I'm modifying? eg buildingCreator = global::BuildingCreatorEditor.GetInstance();
I have never written global:: myself. So I want to know what made this exist
change the language mode to c#? but it looks like hybrid of cpp and other languages
It refers to the global namespace
This is used to specify the global namespace
I understand. but I did not type it, so my IDE put it in there.
in a different file that I was not editting
Like if you had your own System namespace inside another namespace, then to access Microsoft's System namespace, you'd need to do global::System
print something more useful in the log, like check which sound clip is assigned perhaps before playing?
just googled c# allows such syntax...
my IDE is definitely set to C#
I suspect I accidentally tried to rename a class
but I'm still confused
Yeah sometimes it does that with the Quick Actions. The snippets it inserts contains the most declarative code possible to avoid ambiguities, then simplifies it as much as possible until an ambiguity is found, or until it can't simplify anymore
Like the for code snippet, will insert a for (global::System.Int32 i = 0; ..., and simplify it down to for (int i = 0; ...
ok but can you explain what I personally did to prompt this modification in a file that was not open
Any Quick Action that would modify other files
Updating my method to:
public void PlayCoin()
{
audioSource.Stop();
Debug.Log("1 " + audioSource.clip);
audioSource.clip = coinAudioClip;
Debug.Log("2 " + audioSource.clip);
audioSource.Play();
Debug.Log("3 " + audioSource.clip);
}
log:
1 mixkit-handgun-click-1660 (UnityEngine.AudioClip)
2 mixkit-coin-win-notification-1992 (UnityEngine.AudioClip)
3 mixkit-coin-win-notification-1992 (UnityEngine.AudioClip)
But in the inspector, it still shows handgun:
Renaming with Ctrl+R², adding a new member, modifying a method signature...
i suspect i did the rename
so would you say: 1) putting class into namespace, 2) ctrl + R rename. That this prompts global::NewName
Well, you've assigned it to the coin audio after the first print.. so it'll print the coin audio for the latter two.
If you're referring to the property, maybe check to ensure you're looking at the correct object.
Yeah, but it doesn't play it, it instead plays "click" audio clip
Add the second argument cs Debug.Log(..., audioSource);
I'd say the latter. If I were to do the renaming utility, the operation would be done in 3 steps:
- Expansion. The class name and all its references are prefixed with its explicit namespace structure
class Sample->class global::Sample - Rename. The references to it are resolved and renamed.
- Simplification. The name is removed because there's no ambiguities
class global::Sample->class Sample
Afterwards, click the log and see which object becomes highlighted.
I did add the second argument, but nothing changed in my log
its meant to click the log and check which object is calling the log
indeed there might be a clone?
Add a Debug.Break() after play.
there is a DDOL in Play, maybe that has something to do wit it
It the same object that I was inspecting before
Also, show an image of the console logs
Hello guys, I am following code Monkey's tutorial ( this https://www.youtube.com/watch?v=AmGSEH7QcDg&t=405s ) , and I have a problem I have been trying to find a solution for 1 hours now lol, I would love some insight / hints from experienced people, Am I allowed to ask my question here ?
💬 This was a ton of work to make so I really hope it helps you in your game dev journey! Hit the Like button!
🌍 Course Website with Downloadable Assets, FAQ, Related Videos https://cmonkey.co/freecourse
❤ Follow-up FREE Complete Multiplayer Course https://www.youtube.com/watch?v=7glCsF9fv3s
🎮 Play the game on Steam! https://cmonkey.co/kitchencha...
Can you show the entire console window?
Ensuring that it doesn't get played then stopped immediately
Again, it does get played, but it playes another clip, the "click" clip instead of the "coin" clip
With the debug break, what does the inspector show for the object?
I added debug break:
public void PlayCoin()
{
audioSource.Stop();
Debug.Log("1 " + audioSource.clip, audioSource);
audioSource.clip = coinAudioClip;
audioSource.Stop();
Debug.Log("2 " + audioSource.clip, audioSource);
audioSource.Play();
Debug.Log("3 " + audioSource.clip, audioSource);
Debug.Break();
}
And the inspector still shows the wrong clip, and the wrong clip gets played
i got Animation set up but it changes idle animation instant to walking animation and doesnt stop how to fix?
Maybe yield a frame
Didn't work
public IEnumerable PlayCoin()
{
audioSource.Stop();
//Debug.Log("1 " + audioSource.clip, audioSource);
audioSource.clip = coinAudioClip;
//yield return new WaitForEndOfFrameUnit();
yield return new WaitForFixedUpdate();
audioSource.Stop();
//Debug.Log("2 " + audioSource.clip, audioSource);
//Debug.Break();
audioSource.Play();
//Debug.Log("3 " + audioSource.clip, audioSource);
}
Or use PlayOneShot()
If you need multiple sounds at once, one set in the Audio Source, and another that should be played from code, then you should be using two distinct sources
Define worked? I'm assuming no sound played at all...
It plays the other sound effect, not that one that I'm setting
It sill plays the other sound effect
Yes because OneShot overlays the sounds
What if a game has like 15 sound effects per scene, there should be 15 game objects with 15 audio sources?
Use the debug break and see what clip is assigned to the audio clip - assuming all prior images were not during runtime
No, one source with multiple clips fed in OneShot
With play scheduling made in the code, if you don't want them to overlap
This is during runtime, and with Debug.Break, before and after Play
Not sure what's going on. Simply changing clips seems to be an issue that you're having overall.
The playing of the correct clip will be resolved if you can determine why swapping clips isn't possible
Now I'm using OneShot everywhere, still the same result
public void Play(bool shouldDestroy)
{
//audioSource.Stop();
//audioSource.clip = clickAudioClip;
//audioSource.Play();
audioSource.Stop();
audioSource.PlayOneShot(clickAudioClip);
// I believe below is to continue playing the sound effect in the next scene, and then delete the object.
this.shouldDestroy = shouldDestroy;
DontDestroyOnLoad(gameObject);
}
public void PlayCoin()
{
//audioSource.Stop();
//Debug.Log("1 " + audioSource.clip, audioSource);
//audioSource.clip = coinAudioClip;
//yield return new WaitForEndOfFrameUnit();
//yield return new WaitForFixedUpdate();
//audioSource.Stop();
//Debug.Log("2 " + audioSource.clip, audioSource);
//Debug.Break();
//audioSource.Play();
//Debug.Log("3 " + audioSource.clip, audioSource);
audioSource.Stop();
audioSource.PlayOneShot(coinAudioClip);
}
Post the entire script using !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.
HOLY
I'm guessing that you're stopping and reassigning the clip to gun
removing stop here, made it work properly
Although I'm not sure why
But the problem seems to be solved
Thank you for your time@dusk apex @simple egret @rigid island
nice glad you got it working
what an odd thing, even though I just use PlayOneShot mostly
which Stop did you remove?
https://gdl.space/jadexabaza.cpp I can't get the aim down sight to work. When i shoot, the camera doesn't stay fixed onto the sight, which is the aimpoint. adsPosition is the position of the gun when aiming.
whats wrong it only does idling animation and doesnt switch to walking when pressing w
Hey guys, I have an issue currently with TwoBoneIKConstraints.
In editor everything works fine, but whenever I build the game and the Weight is set to anything else than 0, the game crashes. It worked perfectly for about 3 months and it started happening when I implemented a save system with PlayerPrefs (which do no modify anything related to TwoBoneIKConstraint). Any help to debug / fix this issue would be greatly appreciated.
this is literally trying to set a bool named "IsWalkingHash"
i presume you meant to use IsWalkingHash
Both statements require your animation state to be is walking.
Assuming is walking is false, neither will run and you'd stay idle
Yeahh that's a lot of code to do a simple thing, this can be simplified down to anim.SetBool(IsWalkingHash, Input.GetKey("w"))
That single line
Also as your IDE suggests (three dots below Input), prefer using the enum for the key, instead of a string. KeyCode.W
stop and think about what this line of code does
If you don't understand, ask
im clueless about these lines i only know movement ones these sound really wierd to me
i dont this ones right either
okay i got it to do walking animation but it doesnt do idle animation or stop doing animation when pressing w
That would be an Animator setup issue because, ignoring the simplifications this code could use, it's correct
i changed get getkeys to getkeydown and getkeyup
in the animator you'd have your idle state (usually the entry point) where if you've conditions for when you're not in any current state to fallback into it
it's a little confusing because you still have to mimic a lot of the state logic script-side, so your script does end up looking similar to how the animator blend tree would look like. The benefit of this though is it's easier to trigger one-off animations and jump rightback into the previous animation.
my unity overlap sphere has a dead zone for some reason, if another object is too close to the center it stops working and doesnt detect the object anymore
click the arrows in between and make sure the transitional logic is correct
i have left arrow on IsMoving false and left arrow is IsMoving true
All of them
public void Play(bool shouldDestroy)
{
audioSource.PlayOneShot(clickAudioClip);
// I believe below is to continue playing the sound effect in the next scene, and then delete the object.
this.shouldDestroy = shouldDestroy;
DontDestroyOnLoad(gameObject);
}
public void PlayCoin()
{
audioSource.PlayOneShot(coinAudioClip);
}
if you keep the animator tree open side by side as you can see the routes it tries to take. Without knowing more I can only guess that the idle clip isn't set, or there could be an exit lag problem on the blending timeline
yea it skips idle and goes straight to walking and then cant find back to idle
now it shows this
ty
Pretty self-explanatory, the parameter you're referring to in code does not exist in the Animator Controller
i did it
thanke chön
thanke chön pt2
hello! im trying to create a game with cars and i want to add to the main menu some kind of way to select cars and preview them in 3d something like this: https://youtu.be/wjwf4AKfNF4?si=FIa4lyfOhvwowfOm&t=133
Fixing the UI for the mobile racing/drifting game Drifto
https://play.google.com/store/apps/details?id=com.UnluckyDuck.Drifto
https://apps.apple.com/app/drifto/id1643464834
The game is built with the Unity game engine (2019)
does anyone know how could i do this
or have a tutorial which i could watch
you give me idea for a video xD thx
anyway its not diffcult to make at all
they pretty much explain it in the video
they just use a scrollView component for the sliding UI
the cars are rendered with RenderTexture which is a special texture that can be outputted to from the camera/gpu
Would like some feedback on whether this is a decent strategy. So I'm continuing my quest to implement saving and loading. I have a number of modular systems that presently handle their own saving and loading internally. However, this creates many save files, and it'd probably be better to store them all in a single save file per run. That naturally would require coupling.
However ...
I am considering using interfaces and injection. So you have an ISaveable interface that has Save, Load, and Clear methods. Each System inherits from this. Then each system has a corresponding save interface that the central repository inherits from: IGlobalSettingsData, IPlayerPositionData, IInventoryData, etc. The specific interface gets injected.
public class SaveObject : IGlobalSettings, IPlayerPositionData, IInventoryData, ...
{
public IGlobalSettings ...
// Local properties gotten from and sent to the SaveObject
public void Save(){
// Assign each property to IGlobalSettings
}
public void Load(){
// Get each property from IGlobalSettings
}
}```
However ...
Interfaces can't store fields and, from my understanding, you can't serialize properties to something like JSON. So I would have to convert to a backer field inside the SaveObject class. I am aware that C# allows you to do this:
```[field: SerializeField] public int MyField { get; private set; }```
However, if I go to serialize MyField into a JSON string, will that work or do I need to explicitly make a local serializable field for it?
just use Json.net (It can write properties just fine)
JsonUtility is hot trash
@heady iris you were right yesterday about using an Enum
not sure if you remember
but representing "flavors" of something via instances of a thing - and the collection of those things being a List<Thing> just adds so much unecessary complexity
enum solves basically all of those problems
And for putting it all in the same file, I suggest doing it by compressing the contents into a ZIP archive with the stuff in the System.IO.Compression namespace. If you haven't got any solution in place already, of course
you can also make the enum values into powers of two so that you can use it like a bitmask
very handy if you need multiple-choice
I think there is a lot of merit to using more complex datatypes, but only when you actually need more expressiveness
this is all that isCorridor stuff I was mentioning yesterday (I still think the instructors bool implementation is the worst version)
you're right, it is terrible design
i ended up making them all types like Corridor, and doing the matching via thing is Corridor for the logic
yep
my hesitency for Enum was just because I wasn't sure if he had a good reason that he would reveal later on
spoiler: he didn't
another problem with my "typed" solution is that Unity gets annoyed when you orphan classes in one big file
it really urges you to break them out into files named after the class
so that was kind of a waste of time
and even if there is special logic associated with each Enum member - I can solve that with a static function from Enum -> Whatever
You can move from an enum to a more elaborate type if necessary, after all
(maybe scriptable object assets)
yeah this is all SOs
I'm making pretty heavy use of those in my current game
it's nice to be able to just serialize a localized string on something instead of having to look up a translation at runtime with a hardcoded string
i think the course is still worthwhile, since I'm learning some unity tools I wasn't aware existed (like creating a new editor window that does custom stuff)
editor windows are fun
this is like a level-editor tool he's making
you will get exposed to a lot of "unity plumbing" as you get into editor tooling
stuff that you're normally not exposed to, like serialized objects and serialized properties
yeah like the whole EditorGUI.BeginChangeCheck() stuff is neat
forget all that old crap, if you're doing Editor tooling today you should be using UIToolkit, it's far superior
I really gotta learn UIToolkit
I've used it a little for making custom property drawers, but not for anything substantial.
i didn't even know there is a new one
he's using the old input system too
if you've ever done any web dev (HTML/CSS/JS) it's a doddle
EditorGUI/etc. is "immediate mode" GUI
you draw it every single frame
this is simpler to reason about than "retained mode" GUIs, where you just set it up once and then reference the things you created
but you also have to draw the entire GUI every frame.
googling UIToolkit
it also results in some rather confusing code
OnGUI gets called multiple times, IIRC
since Unity has to first figure out how much space things will take up, then paint them
UIToolkit is basically HTML flexboxes.
and runtime UI for games and applications.
people using this for in-game menu?
(Unity UI is also basically flexboxes)
You could never do this with JsonUtility 😏
public class Saving : MonoBehaviour
{
private void Awake()
{
var data = new SavingData()
{
ImAProperty = "Hello From Property :)",
};
data.ImADictionary.Add("Hello", "Hello From Dictionary");
var jsonData = JsonConvert.SerializeObject(data);
File.WriteAllText(Path.Combine(Application.persistentDataPath + "/File.json"), jsonData);
}
}
public class SavingData
{
public string ImAProperty { get; set; }
public Dictionary<string, string> ImADictionary { get; set; } = new();
}```
Definitely switch over to Newtonsoft if you plan on doing real saving system
one of the things I love about UIToolkit is it's so easy to make and consume your own widgets, makes life so much easier
- IMGUI: immediate-mode; anything using
GUI/EditorGUI/ etc for both games and editors - Unity UI: retained-mode; RectTransforms and LayoutGroups for games
- UIToolkit: retained-mode; VisualElements for both games and editors
looks like the official unity youtube video is using it in the context of an in-game menu (so it can do editor stuff and game stuff)
UIToolkit is awesome, confusing a bit at first but def puts IMGUI to sleep
i guess i'm using IMGUI in this course
having actual automatic layout is nice
I've gotten a very good handle on Unity UI, so now I've got that sunk cost going
i bet that ebook on the unity resources page (the one about making an advanced UI) is using this
the binding handling is so much more straight-forward, also very intuitive if you come from XAML
their youtube example looks like the same assets
I've done a shed load of IMGUI in the past, tbh I'm glad to see the back of it
that ebook you linked @rigid island is great BTW. been reading it daily
I still use traditional UI because im used to it but im making all my custom editor in uitoolkit
glad it helped out! they have tons of those
they have a pretty nice blogpost on the ui stuff
https://blog.unity.com/engine-platform/new-ui-toolkit-demos-for-programmers-artists
so glad they also added the UI Toolkit editor so you can visual build it
That's what I'm doing right now. I really like how it's set up. I just have to find a preference: utilize the editor, or code the ui with uss . . .
Same 😅 I tried doing it all in C# without UXML and it came out to be kind of a pain and giant class to mantain, dont mind UXML since it gives that feel of XAML so I feel familiar having done most of my work in the new windows UI / Maui
How would i go about getting and preserving the player's local y velocity, i am making a game where you can walk on a planet (player is a child of the planet), currently the movement works fine but when i walk to the side of the planet the physics start to act weird (eg. player starts to fall diagonally, player jumps diagonally from the pov of the player), i want to preserve the player's y velocity but somehow in local space? how do i do this?
movement method:
Vector3 moveDir = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")).normalized;
Vector3 targetMoveAmount = moveDir * walkSpeed;
moveAmount = Vector3.Lerp(moveAmount, targetMoveAmount, Time.deltaTime * 8);
private void Movement()
{
float currentYVelocity = rb.velocity.y;
Vector3 newVelocity = orientation.TransformDirection(moveAmount);
newVelocity.y = currentYVelocity;
rb.velocity = newVelocity;
Debug.DrawRay(transform.position, newVelocity);
}
How do I use JSON.net? Is that a package in the Unity Registry?
hey @heady iris i deleted my audio folder and my project runs fine
but the audio folder isnt corrupted
add the package by name yes
the name is what comes after the /
so com.unity.nuget.newtonsoft-json
Preserving player's local y velocity correctly
When you say add it by name, does that imply I can't access it through the Package Manager window?
Explain it to me like I'm 5, basically.
no, that is an option within the package manager
Is it this one? Cuz I don't see any other options for JSON, .Net, or Newtonsoft.
Hey, I'm working on a deck builder game where there's a deck for the entire run and it gets cloned for a battle. For some reason, it seems like if a card is modified during a battle, it is also permanently changed, but it shouldn't. Look at the code below where I've put the methods that are called in order, what am I missing?
// DECK CONTROLLER
public DeckController Clone() {
List<CardInfo> deckCardClones = new List<CardInfo>();
// Moved to TryAddCardToDeck.
foreach (var card in _deck) {
deckCardClones.Add(card.Clone(CreatedBy.DECK_CLONE));
}
return new DeckController(deckCardClones, _skipShuffle);
}
// THE CARD
public CardInfo Clone(CreatedBy createdBy = CreatedBy.UNKNOWN_CLONE) {
if (createdBy == CreatedBy.DECK_CLONE) return new CardInfo(this, createdBy);
var cI = GenerateCardInfo(_cardData, _owner, createdBy);
cI.SetCreatedBy(createdBy);
return cI;
}
public CardInfo(CardInfo cardInfo, CreatedBy createdBy = CreatedBy.UNKNOWN) {
_owner = cardInfo._owner;
_createdBy = createdBy;
_isUpgraded = cardInfo.IsUpgraded();
AssignVariables(
cardInfo.GetCardDataForArt(),
cardInfo.GetCardId(),
cardInfo.GetCardName(),
cardInfo.GetManaValue(),
cardInfo.GetShuffleTypeValue(),
cardInfo.GetSpeedValue(),
cardInfo.GetElement(),
cardInfo.GetKeywords(),
cardInfo.GetCardDataForArt().tetheredCard
);
InitializeEffectControllers();
}
Yes, the file can quickly build up when creating the UI in C#. It helps to use the builder pattern with extension methods to quicken the process
I use the UI builder myself. The layout is so much easier than before. Once I figure out accessing the binding properties to alter/ update the design based on field values, I'll be good . . .
Did you find it, if not look at what Fen sent
Yeah Im glad they added UI Builder, it makes everything much easier if you can see it visually .Very good tool
good tip on the builder pattern, I should've just done that 😅
[SerializeField] private LocalizedString m_PasswordErrorText;
How do I get the string from this ?
PopupManager.MyInstance.AddToQueque(m_PasswordErrorText.TableEntryReference);
Does not work ? AddToQueQue is a string
what exactly "doesn't work"
TableEntryReference is not the localized string
It's a key used to look something up in a string table
m_PasswordErrorText.GetLocalizedString() will work
Ohh LocalizedString is a Unity class dooh. I thought it was custom class
Hey I am trying to make a random scrolling animation that selects a item (like what it looks like when choosing a mini game in Mario party) does anyone know how to make it or better yet a tutorial.
scroll rect
or do you mean the code
no idea what minigame selection looks like in MP 🤷♂️
Oh just a sec I will get a video
This video is a complete full game walkthrough for Mario Party Mode in Super Mario Party for Nintendo Switch in 1080p & 60ps. This video features many characters from the Super Mario Bros. Movie. Thanks for watching. Are you excited for the Super Mario Bros. Movie and looking for Mario content? I've got it tons of videos from all of your favo...
oh that looks even easier lol
literally just scrolling through a simple list and adding the visual highlight for the indexes
break down the issue into smaller steps, I don't think you would find such a specific video.
pick the random item is the easy part ofc, the hard part is smoothing the UI to look just right
Oh wait that sparked something I might know how to make it thank you
Yes, I did. Thank you.
Now I just have to figure out how to use it. 🙄
did you click "Documentation" ?
also my example shows, its literally 1 method
you're basically just swapping JsonUtility static function with this class instead
So as simple as just replace this line?
TO: string json = JsonConvert.SerializeObject(saveObject);```
yes exactly
i have a Game Manager type script that i send events and names and IDs and such to. There is a significant amount of boiler plate code involved in doing this, every time. Is there a set of built in functions i am not aware of that does things like ('object a-script a), get info variable somename from (object b-script b)'?
What does your current code look like?
private void Start()
{
// Find the GameObject with the "Player" tag
GameObject playerFarmer = GameObject.FindGameObjectWithTag("Player");
if (playerFarmer != null)
{
// Access the GameObjectInfo component and call ReturnName
GameObjectInfo gameObjectInfo = playerFarmer.GetComponent<GameObjectInfo>();
if (gameObjectInfo != null)
{
// Get the name from GameObjectInfo
string playerName = gameObjectInfo.ReturnName();
// Use the playerName as needed in the Odin script
Debug.Log("Player Name: " + playerName);
}
else
{
Debug.LogError("GameObjectInfo component not found on the Player-Farmer.");
}
}
else
{
Debug.LogError("Player-Farmer GameObject with 'Player' tag not found.");
}
}
create extention classes/methods
I was thinking that, that was probably the way.. now i have to figure out exactly how 😅
Beyond architectural changes, some basic syntax changes will make this a lot more palatable:
- Have a method
GetComponentOnGameObjectWithTag<T>(string tag)so you are not repeating the same finding and checking code over and over. - In the implementation, make use of guard clauses.
Hello, does anyone know which are the JoystickButton numberd for the arrows on the left of a PS4 Joystick?
Thanks., I will start attempting to implement that now
Ok, i think i got it. still finalizing testing
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GOUtility : MonoBehaviour
{
public static T GetComponentOnGameObjectWithTag<T>(string tag) where T : Component
{
GameObject[] gameObjectsWithTag = GameObject.FindGameObjectsWithTag(tag);
foreach (GameObject go in gameObjectsWithTag)
{
T component = go.GetComponent<T>();
if (component != null)
{
return component;
}
}
return null;
}
}
GOUtility does not have to be a MonoBehaviour unless it has specific reasons to, otherwise it can just be a plain C# class. Make it static too if it's not meant to be instantiated.
Thanks., i will have to go a bit further to determine whether it will eventually require MonoBehaviour or not. Changing to static now. Edit: Oh, ok, making it static insists on removing MonoBehaviour
Hey, I want to make a button that when its clicked it checks the other button to see if the material color is green. If it is then it turns green but if its not they both go red but it seems like the second one still turns red.
!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.
Is there an equivalent to Rigidbody.AddForceAtPosition for rotational velocity? One that would change both velocity and angular velocity as one would expect when trying to rotate an object away from the center of mass? I see Rigidbody.AddTorque, but unless I am mistaken, that only changes angular velocity. Is there maybe a way to calculate the force and torque manually? Also, is anyone having issues where docs.unity3d.com is just not loading? The docs for Rigidbody.AddForceAtPosition is still showing the loading icon, and the page for Rigibody isn't loading at all.
the page comes up fine here https://docs.unity3d.com/ScriptReference/Rigidbody.AddForceAtPosition.html
I just tried on another browser and it worked fine, I guess one of my browsers is having a hard time :\
rotten cookies
Doesn't look like it was a cookies issue. It will probably start working again for no reason the next time I restart my pc.
Link didnt load for me.
Watched this yesterday and it might help accomplish the same tasks without having to look up the information via find:
https://learn.unity.com/tutorial/persistence-saving-and-loading-data#5cf18288edbc2a3094da073b
that link works here.. checked after you mentioned it
Cool deal, thanks. I will check it out right now
Ah, yeah, that is a different subject entirely, but good to have in the links
I don't see in this code where you are comparing to another button, just the button color itself.
ended up doing this
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class GOUtility
{
public static T GetThisComponentFromGameObjectsWithThisTag<T>(string tag) where T : Component
{
GameObject[] gameObjectsWithTag = GameObject.FindGameObjectsWithTag(tag);
foreach (GameObject go in gameObjectsWithTag)
{
T component = go.GetComponent<T>();
if (component != null)
{
return component;
}
}
return null;
}
}
which allows me to get the variables of the dynamically instantiated game objects with the much shorter method of :
string playerName;
private void Start()
{
GameObjectInfo playerGameObjectInfo = GOUtility.GetThisComponentFromGameObjectsWithThisTag<GameObjectInfo>("Player");
if (playerGameObjectInfo != null)
{
playerName = playerGameObjectInfo.ReturnName();
Debug.Log($"Player name is {playerName}");
}
}
pretty new to programming, so the verbose names help me think it through
I'm also new, whats the benefit to this, when you can just do
GameObject.FindGameObjectWithTag("Player").GetComponent<GameObjectInfo>().doSomething();
other than it being ugly 😆
this is also coming from the guy whos inventory script controls building as well
It looks like his searches through all with the tag to find one with the component, where as that would break if it first found an object with the tag but without the component.
Ah, yeah makes sense to condense searching all gameobjects with tag player then checking their components in its own method*
Though I do recomment using .TryGetComponent<T>() and using the boolean output rather than comparing with null.
There's probably some Linq shenanigans that could make that in one line if you were really deticated.
Maybe this?
GameObject.FindGameObjectsWithTag(tag).Select(x => x.GetComponent<Rigidbody>()).FirstOrDefault(x => x != null);
I have a question my building system checks for collision and if it collides with an object (the player moves the mouse and it casts a ray) I have a bunch of conditionals to check what object it hit.
Heres a really condensed version
if (hit.collider != null && hit.collider.gameObject.transform.parent != null)
{
if (hit.collider.gameObject.transform.parent.gameObject.CompareTag("Carpet"))
{
if (activeItem.name.Contains("Carpet") || activeItem.name.Contains("Floor") || activeItem.isWalkable)
{
return;
}
}
}
...
(checks parent object as objects can have a physical item pickup collider)
What can I do to make this less convoluted?
in this specific condition, if the player holds an item that is a carpet, floor, or its walkable, it will return making it so it cannot be placed
@jade vault
Physics.Raycast returns true if it hits something, which can replace hit.collider != null.
I believe you could do hit.collider.gameobject.transform.parent?.gameobject.CompareTag("Carpet") to avoid checking if the parent is null, the question mark tells it to evaluate to false if it gets null there.
Ah, thank you. I am using Physics2D, does that change things?
I'm sure they are identical in some ways.
hmm. probably not much (beyond the null checks). i am just new enough to have to stick with the first thing that makes sense for a while, until the 'other' thing starts to makes sense 🙂
It also does not handle null, if for example the player game object is not found, it would proceed to throw NRE.
Yes, slightly. The function won't return a boolean, but RaycastHit2D is truthy if it hits something, so you can just do if (hit)
And you also cannot fix that with ?. because Unity.
Aw, unity shenanigans :\
Dang, I could just make it so instead of checking objects that would cause it to return, check if it the hit is a placeable area and return everything else
What exactly is wrong with it? Does Unity's version of c# not support it? Does .parent return some weird value instead of null?
My building script is 1,600 lines like 400 lines for sure is just conditional statements checking if an object is there
I simply do not understand that well enough to use it yet 🙂. soon, perhaps
Presumably in this case using ?. is safe, because I would think FindGameObjectsWithTag and friends would not return GOs that are already dead.
But that would mean you need to suppress analyzer warnings and what not, so yeah I would not recommend.
You would use referenceequals if you cared about real null
Or is null.
real null?
C# pattern matching is great 😄
The array ones will just return an empty array, but anything that doesn't may return Unity null for more context
Not a destroyed object, but a fake one that specifies the origin of the call
Managed objects will refer to an object as null while the the native compilation would keep a reference to the object
It's the opposite
The managed object exists but will evaluate to null via the overridden equality
Oh
Interesting, well it's pretty much to the point you have to know the implementation details of those methods to use ?. safely, so I guess the verdict is "just don't."
So does garbage collection cause the high-load times with Instantiation as it takes CPU time? Or is it loading that object what causes it to lag.
I think garbage collection is asynchronous.
In a simple 2D sprite renderer object in this case
There is nothing collected when you instantiate. The cost is loading the object and allocating memory
Ah, implemented Object Pooling into my game to remove frame drops when building. Still get frame drops.
Have you profiled?
Yes heres a video
Yeah, I sent my comment at the same time you sent it. Watching now
No prob my b
Why on earth would it think that the 3rd Log is not contained within the other 2?
What?
The white dots are TL and BR
I declared a rect covering this area
and when I click inside it, it calls the function that SHOULD be called when i click OUTSIDE of it
the third log is the mouse position
first is top left, second is bottom right
the mouse position is in range of the other two
so why does it think its outside the rect
Does this new Rect(SimBoundsTL, SimBoundsSize); do anything? Is it creating an object and doing nothing with it?
Does .Contains do what you think it does?
I'd hope so lol
I'm not sure exactly what SimBounds holds, but .Contains() usually determines if an item is in an array/list/generator
Rect.Contains just checks whether a vector lays within the Rect
What happens in Bag.Update()
Seems like that is the issue, not instantiation?
Also looks like you could have drilled down further in the hierarchy view? Kinda hard to watch it on my phone haha
That looks correct then. Are you sure you are creating the rect correctly?
@spring creek Yeah I could have sorry about that. In Bag.Update it runs the function to check if an object can be placed and then instantiates that object. It also will then update the items in the bag and then updating the slots. When the slots get updated it does instantiate new slots. However, those are also pooled.
it says its declared with Rect(x,y,width,height)
and thats what i've done
This is such a stupid thing to be stuck on for hours I have no clue what the problem is
this is GUI space, while you are using it in world space
I've tried it in both honestly
In your code, I see you create a new Rect, but you don't actually assign it to anything.
variable = new Rect(...) creates a rect and assigns it to variable.
new Rect(...) just creates one and doesn't actually put it anywhere, so it might as well not exist.
Did you mean to write SimBounds = new Rect(SimBoudnsTL, SimBoundsSize);?
wtf
u are so right
my god
i declared it at the top
but never gave it a value
ty
@spring creek ah, a new deep profile has discovered the issue. Must have been an editor glitch, it was displaying Instantiate instead of the actual issue. Its my AStar pathfinding updating the region where AI (animals) can walk.
Now to research a quicker way to do that 
Aaaaand you can just take it off the main thread. Out of the box.
Updated. Thanks
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class GOUtility
{
public static T GetThisComponentFromGameObjectsWithThisTag<T>(string tag) where T : Component
{
GameObject[] gameObjectsWithTag = GameObject.FindGameObjectsWithTag(tag);
foreach (GameObject go in gameObjectsWithTag)
{
T component;
if (go.TryGetComponent(out component))
{
return component;
}
}
return null;
}
}
Ok nice. That does make more sense. It wasn't instantiating that many things quickly
If you want to make it even fancier, you can define it in the same line as you call the function.
You can write out T component and by giving it a type, it will create the variable in the same line.
Thanks @spring creek
Really!? I did not know that. Ok, trying
Nope., i will have to save that one for later, as i do not understand the syntax well enough. I will keep it in mind though 🙂
wait, did you mean like this?
foreach (GameObject go in gameObjectsWithTag)
{
if (go.TryGetComponent<T>(out var component))
{
return component;
}
}
Yes. var implitly converts to the type of what is being assigned, so it's basically the same as writing T. If T wasn't working, it might be some weird edge case related to generics.
you can remove the <T> and replace var with T too
that was my first try, and for some reason, it did not seem to like it, so i ended up with this syntax. I will try again though, as there is a good chance it was my own user error
Hah. as expected, user error. Seems to be working that way now 🙂
public static class GOUtility
{
public static T GetThisComponentFromGameObjectsWithThisTag<T>(string tag) where T : Component
{
GameObject[] gameObjectsWithTag = GameObject.FindGameObjectsWithTag(tag);
foreach (GameObject go in gameObjectsWithTag)
{
if (go.TryGetComponent(out T component))
{
return component;
}
}
return null;
}
}
That really does make a lot more sense than a null check. Thanks again @ Burrito, Frog Detector, vertx and all
Can I suggest the name GetCompontOnObjectsWithTag
Just a thought. It aligns more with the two methods your combining
good idea, thanks. I just had it named that way to cement my understanding of the concept 🙂
public static T GetComponentOnObjectsWithTag<T>(string tag) where T : Component
Totally fair. Doesn't really matter either way, just popped in my head so I shared it haha
updated now, because you were correct. makes more sense matching the rest of the names 🙂
Try pattern vs get then null check are pretty much just two different ways of writing the same thing, except one critical difference: try pattern allows you to represent success state but with a null result value.
In this case that is not really utilized, so either is fine.
Personally I find try pattern to be a bit icky because of the inline variable declaration, so you have to read to the end of the line to see it.
For some reason, i was under the impression that is was more efficient, in the long run, than != null. that was just my impression, i am not suggesting that as fact. i surely do not know
Was taken away for a moment, yes I am comapring the color of the button
why is this guy using this line of code:
instead of using this?
transform.Translate(Vector3.forward * flySpeed * Time.deltaTime);
not sure if I wrote the code correctly but you get the point
what even is +=?
if i make a prefab of an object with a collider and trigger on it, how come it doesnt work the same as the original? My code opens a menu when close to an object after a key press. The copy does not
x+=1 is just shorthand for x= x+1
If you look at what Translate does its the same https://github.com/Unity-Technologies/UnityCsReference/blob/7c95a72366b5ed9b6d9e804de8b5e869c962f5a9/Runtime/Transform/ScriptBindings/Transform.bindings.cs#L147
Well do you get any errors? Also show the relevant pieces of code. A prefab should work the same as the original
Translate is a mathematical term that means to move a point in space
i found out why, I have an object from the desk script that if I used a list instead of a single object it would open up on any desk
You move a point in space by adding to its coordinates
Am I allowed to ask custom editor related questions here?
alr
No, since Translate operates in local space of the object by default
I have a hidden tilemap but when I click on the IsActive button, it stay hidden. Do somebody know why ?
How is the tilemap hidden? Just with IsActive turned off or is the tilemap renderer disabled?
Is active is off
Then probably some other script is turning it off. You can try putting the object in some empty scene without other scripts to see if it behaves the same. If it behaves differently, then you'll know that something is messing with it.
ok thx
hello my fellas. i'm working to create a mechanic where an enemy will try to hide from the player when looked at. currently i'm just trying to figure out how to check if the player can see the object. my research has suggested i use raycasts, but that doesn't feel like the right thing to use. i'd like to check if it shows up on screen, not just if the player is looking directly at it. any guidance would be greatly appreciated
You could check if the renderer is visible (it's a built in field) or possibly use this
https://docs.unity3d.com/ScriptReference/Camera.WorldToViewportPoint.html
Although the last one might have slight edge cases where you can see a part of the object but not the center which you'll have to handle how you want that to function.
You will need to raycast at some point though, especially if you're trying to have it hide. Otherwise you dont really have a way of checking what areas are visible. Also with the last method I linked, you'll need to raycast so the ai doesnt think its visible but its on the opposite side of the wall
Let's explore how you can detect when an object is inside the players camera view by using the camera's frustum and axis-aligned bounding boxes (AABB). This takes advantage of Unity's built in GeometryUtility class that provides some helper functions to make this easier.
The fi...
What is the best way to change "ErrorMessages" ?
try { await UnityServices.InitializeAsync(); await AuthenticationService.Instance.SignUpWithUsernamePasswordAsync(m_RegisterUsernameInputField.text, m_RegisterPasswordInputField[0].text); Debug.Log("SignUp is successful."); } catch (AuthenticationException ex) { Debug.LogException(ex); } catch (RequestFailedException ex) { // Compare error code to CommonErrorCodes // Notify the player with the proper error message Debug.LogException(ex); }
What? The exceptions you get cannot be modified, so you will have to make your own depending on the error code, as the comment suggests
How do I catch i have tried it with string .. if (errorCode == "INVALID_PASSWORD") .. but this does not work
This really depends on the exceptions. If it does not have an error code or anything like that you can't do this
The code will be inside ex so see what's inside that first
So if AuthenticationException can specify what went wrong, you can check for that.
Or maybe it falls under another exception type. Consider reading the documentation of what it can throw, perhaps
And the RequestFailedException will most likely have the HTTP status code in it.
Like 500 Internal Server Error, 404 Not Found, etc.
Yes but how can i catch it in a if statement ?
You look at the documentation to see where in RequestFailedException it is
catch (AuthenticationException ex) { if (ex.ErrorCode.ToString ==) } catch (RequestFailedException ex) { // Compare error code to CommonErrorCodes // Notify the player with the proper error message Debug.LogException(ex); }
This is the errorcode:
[Authentication]: Request completed with error: {"detail":"Password does not match requirements. Insert at least 1 uppercase, 1 lowercase, 1 digit and 1 symbol. With minimum 8 characters and a maximum of 30","details":[],"status":400,"title":"INVALID_PASSWORD"}
status: 400
Your exception variableexshould have aStatusproperty, as well as aTitleproperty. You need to check those in your if statement
if (ex.Title == "INVALID_PASSWORD") for example
ex.Title does not exist
That was my question how I get the title or something to change it
Then use the completion list to see what's available
It's probably under another name
string errorCode = ex.ErrorCode.ToString(); if (errorCode.Contains("INVALID_PASSWORD")) { Debug.Log("TEST ERFOLGREICH"); }
This does not work but the error:
[Authentication]: Request completed with error: {"detail":"Password does not match requirements. Insert at least 1 uppercase, 1 lowercase, 1 digit and 1 symbol. With minimum 8 characters and a maximum of 30","details":[],"status":400,"title":"INVALID_PASSWORD"}
Just look at the documentation it will be much faster
Where do I find it ?
On the internet
is this a bug with unity?
My script very clearly inherits monobehavoir and is in the right namespace
my IDE sees no issue and I tried restarting unity & discarding VCS changes and rebooting also
it just won't recoginize this file for some reason
Did you try without the namespace
I don't think it's a good idea to use Unity's namespaces in your own scripts
I can definetly try, its weird though since other scripts are using the same namespace in the folder and work totally fine
apparently that fixed it? so am I just not able to use the namepsace scenemanagement without conflict?
its odd I never got a warning from unity before or smth
also even weirder is it worked yesterday
and only one file broke
Sometimes such issues can be fixed by reimporting corrupted file. Bugs happen.
Can anyone help me with detecting if my character has rotated 360 degrees within a certain time frame?
to then trigger an ability
ok ill check that out
Well, some requirements I'd set is a counter that accumulates degrees rotated over the time frame. Not sure how you'd want to handle if a character rotates an opposite direction such as reseting the counter entirely.
Or just decrement the degrees
ok thx
ok so im sorry but i have 0 clue as to how i would implement that with this gameplay. (The ability should trigger once the mouse has rotated around the player)
huh, that worked, thank you so much for that little trick! I'm definetly going to get a lot of use out of that
float degreesDif = Vector3.Angle(previousForward, currentForward); //or w/e forward is in 2D
float totalDegrees += degreesDif;
few things though is you need to also figure out if you're rotating in the same direction
alright
such that if you rotate clockwise then add positive degrees, otherwise negative degrees
and both values of 360 and -360 should work
alright man i appreciate you so much, but i think im to stupid too do this and ive been on this for 2 hours. I give up sorry
lol well, you were almost there
well i dont know how i would implement half of the stuff you were talking about
just finding the angle between two vectors
yup, no idea
and adding em up
any idea if you can differentiate between left and right click with an event trigger from code?
if you want to use code then just use the IPointer interface and check the click there
wait nvm
i found it out
apparently you can send pointer event data with event triggers
yup the code is easier public void OnPointerClick(PointerEventData pointerEventData)
its right in the signature
can anyone tell me why this code freezes unity (lastX =999 and currentX = 0 by default, something has to do with the while)
What happens if you call LoadAsset() on an asset bundle multiple times?
bundle.LoadAsset<GameObject>(assetName);
Does it create multiple copies in memory or is only one copy ever loaded?
Can someone explain to me how the inside of the "if" line of code works? I don't understand why we are using a new Vector3 and not Vector3 by its self? and why did he write transform.position.y and transform.position.z instead of just writting 0, 0
If they wrote zero for y and z, they would be overwriting the previous y and z values. They only want to set the x value to negative ten if the x value is ever less than negative ten.
You can not write directly to one axis of a transform position, so a workaround is to set the other axis to their current value (leaving them untouched) and giving a value to the axis you want to modify
can anyone help me pls im in a hurry. ty
You have an infinite loop, which is why its freezing.
yea but why
what's another example where you use transform.position.y and transform.position.z
probably need while(condition1 && (condition 2 || condition 3))
try the parentheses
lemme try
I'm just guessing that is the logic flow you are attempting
like this?
You're welcome. Good luck on getting your logic check correct
Last x is not 999 and any value of current x minus last x results in a value greater than 2 - for instance, you would get an infinite loop if last x was negative ten.
Or if last x was 9
yo can someone help add my idle animation to my character in unity
not the x bot the character that I imported
Don't cross post #💻┃code-beginner message
ok
used a way more efficient approach that worked :)
I have a quick question about using Animator Override Controllers (haven't really used them before), but I have a character who can wield many guns, the number of animations on the character (Run, Walk, Shoot etc.) won't change, but the animation clips for each gun will.
Do I create an Animator for, say, 'Character_Base_Anims', then create an override for each weapon and swap out the animator override when I equip a different weapon? Or is the correct workflow to have 1 animator override, and swap out all of the overridden clips based on the weapon equipped?
One override and swap out the clips
The whole idea is to only create a single animator with all the states that you swap the animations used for each state, via the override controller.
hey, not quite sure where to ask about this but has anyone used strand based hair simulation?
https://github.com/Unity-Technologies/com.unity.demoteam.hair
I managed to setup everything following the tutorial and it works but for some reason i cannot get a material to be applied to the hair, it always just forms a big color block somewhere and the hairs disappear, no part of the guide talks about materials so i assume just assigning one should make it work?
https://learn.unity.com/tutorial/set-up-character-hair
An integrated solution for authoring / importing / simulating / rendering strand-based hair in Unity. - GitHub - Unity-Technologies/com.unity.demoteam.hair: An integrated solution for authoring / i...
Hi, I imported the UnityEngines.Splines package through the package manager, but I can't use any of its types inside my scripts, can't even import its namespaces with using directives... I can however, use its components inside the editor. Anyone experienced this before and has some tips? Many thanks!
wdym you can't use it in the scripts?
try Regen Project Files maybe
is there a specific size at which Hashset.Contains is faster than Array.Contains?
I assume so?

oh god. more benchmarking -.-
hashset is 0(1)
Hashset.Contains should be always faster than array.contains unless you only have two elements.....
.net runtime can't find the assembly... I'll try regen...
it's mostly an issue of overhead
I found some benchmarking
regen also are you using assembly defintions ?
I do have one for the project, but not for the imports
array is still faster at the 10 element mark
gotta pay the c# fee
yeah. array, as always, if best for small numbers
probably cache hit
is the type value or reference?
btw, Unity source code shows this:
1 => (Object)(object)other == (Object)(object)this,
2 => (Object)(object)other != (Object)(object)this,
_ => true,
};```
which I thought was interesting syntax
!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.
Thanks! It was the asmdef... just had to add UnityEngine.Splines to the reference list.
is there a simple way to do this for simple one liners that return void?
No, it's a switch expression so it must return a value
It's not like match x { } in some other languages
any idea on how to load a custom class with resources.load ?
like
CustomClass class = Resources.Load<CustomClass>("class");
^^ doesn't work
i test it with random access, unfortunately hashset is faster the list with count=10
what are you trying to do
an item use system which takes a string and returns an ability from a script in resources
the most flexible way possible ^^
(i don't want to make a scriptable object for every ability)
This doesnt look flexible, looks more fragile than anything. That function is for getting assets. What is CustomClass and how will this provide you with getting an ability?
Scriptable objects seem like exactly what you want here instead
[System.Serializable]
public class CustomClass
{
public virtual void Activate() { }
}
public class Base_Use : CustomClass
{
public override void Activate()
{
Debug.Log("use");
}
}
public class Base_Use_2 : CustomClass
{
public override void Activate()
{
Debug.Log("use 2");
}
}
if i do
CustomClass use = new Base_Use_2();
use.Activate()
it returns "use 2" as expected
the problem is that i cannot asign customclass from an scriptable object in the inspector
also base_use and base_use_2 are separate files
What's considered the best practices when handling user inputs? Should I use scripts to handle movement via Input.GetKeydown or should I use the build in Input Manager? OR is it just preference
Well, you kinda can
any idea on how
via [SerializeReference]
doesn't seem to work
up to you , doesnt matter much.
Look into new Input System though if you want something more modern
[SerializeReference] BaseClass obj = new DerivedClass(); // Or other methods
If you want it to take in a string, then you're gonna have to declare your own mapping from string to new ClassName.
Aside from that part, you could easily just do this all via scriptable objects, and just put the Activate functionality on a scriptable object
Thanks! On the other hand, I wanted to ask about first and third pesron follow cameras, from my exp with tutorials they typically do it with scripts, and I was wondering if there was a "best practice" floating around
its literally the same that i had at the start
like the "new DerivedClass()" thing
Everything is gonna have to be code in some way. Whether you make it or someone else. Use cinemachine, does all the work for you
Why not do it this way then?
because you cannot asign it from the inspector of serializable objects
i might just do an scriptable object for every script and thats it
You can assign it from the inspector, you just have to play around a bit
before that imma look into this
Is there a downside to using cinemachine
I'm not opposed to writing code (I actually love doing it) but just was wondering, figured I'd ask

cinemachin will take care of the heavy lifiting (lerping and all that)
you dont need follow scripts for example
So if I were to use my own scripts I'd be writing to simulate what cinemachine does to a degree right
you plop a target and it follows
no point in reinventing the wheel
Mhm
you still need basic stuff esp for FPV
like rotating the eye view with code etc.
Not really, you just need to learn what to use from all its settings. Theres a lot of options
What I said is just make SO for the functionality, I'm not really sure where the whole string part comes into play. The string part you should remove, unless the user is typing in words to cast an ability.
I have a strange problem, game does only work in editor, doesnt work when built, it looks like from debugging that the Camera Manager would never call the SetupPlayerVirtualCamera() I can go voice chat if that would help
Camera Manager
private void OnEnable()
{
playerTransformAnchor.OnAnchorProvided += SetupPlayerVirtualCamera;
}
private void Start()
{
if (playerTransformAnchor.isSet)
SetupPlayerVirtualCamera();
}```
Player
```cs
public override void Spawned()
{
if (Object.HasInputAuthority == true)
{
playerTransformAnchor.Provide(transform);
}
}```
playerTransformAnchor
```cs
public class RuntimeAnchorBase<T> : DescriptionBaseSO where T : UnityEngine.Object
{
public UnityAction OnAnchorProvided;
[Header("Debug")]
public bool isSet = false; // Any script can check if the transform is null before using it, by just checking this bool
[SerializeField] private T _value;
public T Value
{
get { return _value; }
}
public void Provide(T value)
{
if (value == null)
{
Debug.LogError("A null value was provided to the " + this.name + " runtime anchor.");
return;
}
Debug.Log($"{name} runtime anchor provided with {value.name} transform and OnAnchorCallback {OnAnchorProvided != null}");
_value = value;
isSet = true;
Debug.Log($"value set to {_value} and isSet to {isSet}");
OnAnchorProvided?.Invoke();
}
public void Unset()
{
_value = null;
isSet = false;
}
private void OnDisable()
{
Debug.Log($"RuntimeAnchorBase OnDisable");
Unset();
}
}
I'm just tired with this issue
the call stack has the same order in editor and when built
Why is my text on the last line not centered ? What did I make wrong ?
So I'm rotating around a circle using RotateAround along with MoveTowards to create a spiral effect. I was doing it via rotation + forward velocity but it eventually creates some rotational drift over time. Anyway, assuming my rotating object starts at the very ends of the circle, I want this object to move towards the center pivot at a speed dependent on a duration (normalized time), so it would be distance from pivot / duration.
Now, that works, but let's assume my circle is irregular like an ellipse. Since the radius can differ for where ever it spawns, how would I create a speed that respects where it is on the ellipse, such that it would slow down as it got closer to the pivot, but faster the further away it is.
like I need to normalize speed based on a MAX distance?
oh, wait maybe I just recalculate the speed instead of caching it
right, that's what I get for trying to save those extra few operations
Settings seem fine to me. I would check if you have some extra invisible characters between 2nd and 3rd lines. Similar issues can happen when you copy text from text editors. Try deleting everything between 1-st character of the 3rd line and the last character of the 2nd line (including those characters), then retype the missing characters.
OK did work.
Is it possible to add there some information per script ?
Thats the Unity Player Management Dashbord
There won't be any wait between the color changes, that's not how coroutines work
"co-routine" - runs "concurrently", as in parallel to the current code
StartCoroutine just tells Unity to check on your coroutine method every frame (by default)
When Wait(5f) runs, the Wait method will execute until it hits a yield statement.
It will then return an IEnumerator, which is passed to StartCoroutine. That tells Unity you have a new coroutine for it to keep track of.
This will not stop ChiliRedeem from executing. If it did, your game would freeze.
You need to make this whole method a coroutine, and yield directly in it.
Or, put the second color change inside the coroutine, after the yield
Unity will wait for 5 seconds, then ask the IEnumerator returned by Wait for a new value. The method will exit, so the enumerator will report that it's exhausted. Unity will then decide the coroutine is finished (having done nothing)
Also, this will not do any kind of smooth fading of the colors
It's just going to set the color to something between assignColor and Color.white based on the value of timer
read about coroutines here.
I'm wondering how I would detect these voxels that aren't connected to the rest of the group so I can make them fall down
I am just a beginner here would be interesting how to solve this.
Maybe it fits good here now void Start() { InvokeRepeating("SpawnObstacle", _startDelay, _repeatRate); _playerControllerScript = GameObject.Find("Player").GetComponent<PlayerController>(); } if I start a coroutine like this on a SpawnObject for example it will only give me the ability to set the repeat rate once on start right? What ways are there to keep it more open and be able to change the repeatRate for example if I want to make it spawn faster when difficulty gets higher per kill or whatever
sorry not Coroutine but a invokeRepeating
So it would be better to make a CoRoutine and just update the values of the spawnRepeat in the Update method
right?
interesting one! I'd probably start with the ones connected to the ground, and "mark" them with a "1". Then mark each voxel they connect to with a 2- then go through those "2-marked" voxels and do the same marking thier neighbors with a 3, until I reach a loop where every voxel I'm testing HAS a marked neighbor. Finally, those without ANY "marks" fall down. This is very brute force, obviously, and I've got a feeling, not the most optimized approach.
yes, update would work well for this. You COULD also, choose to make your corotine run an infinitite loop- checking the time, and yielding if the timer has not run out..
really the only neighbors you need to check are those at the top of the brush
first, don’t call methods by strings. That is really error prone, and usually slow. The usual workaround would be nameof(SpawnObstacle). But you’ll usually want to actually find a different way to just call the method.
this sounds like you want to use Update()
private float spawnPeriod;
void SetSpawnRate(float spawnRate) => spawnPeriod = 1/spawnRate;
void Update() {
if (Time.time >= nextSpawnTime) {
SpawnObstacle();
nextSpawnTime += spawnPeriod;
}
}```
a method you run as a coroutine can still see fields from its class; just store the repeat rate there
[SerializeField] float delayTime;
IEnumerator DoSomething() {
while (true) {
yield return new WaitForSeconds(delayTime);
}
}
that is an alternate method
my method requires more maintainance, but gives more control over pausing and changing numbers in the middle.
only KINDA coding Q: I wrote a class, but I hate the name- any suggestions for a more descriptive name? /// <summary> /// Represents a scrollable list of unlimited objects, and displays them using a limited/minimal number of instantiated UI Objects. /// </summary> /// <typeparam name="TListElementType">The type of elements in the full list.</typeparam> /// <typeparam name="TLineElementPreFabType">The type of prefab used to display list elements. /// Must implement the <see cref="IDisplay{TListElementType}"/> interface and must be a Monobehavior, to ensure proper functionality.</typeparam> public class LimitedObjectScrollListBase<TListElementType,TLineElementPreFabType>:MonoBehaviour where TLineElementPreFabType : MonoBehaviour,IDisplay<TListElementType> let me know if more details wold help.
ScrollingCollectionBase
collections by definition contain objects, and have different constraints over capacity
ObjectScrollConstraint
good ones! was hoping to highlight the fact that a limited number of UI elements (just enough to fit on screen +2) will be instantiated, regardless of number of items in the list. should I not worry bout that?
that is just one behaviour of it
not worth putting in the class name
what is it? a collection for a scrollbar
but as an abstract base
oh, it isn’t abstract?
then nvm, don’t put Base in the name
abstract cuz you cannot use generic mono's
i believe you can AddComponent a concrete mono of generic class, iirc
i might be mistaken. but i think that’s how it goes
in my case, I do keep all my generic monobehaviours abstract, to force inheriting into a concrete
i just noticed a lack of abstract in your signature
I've been creating concrete descendants and adding em into the canvas, at editor-time.
then add abstract to the declaration
right now you can instance it, and AddComponent during runtime
like this guy public class LimitedFileScrollList : LimitedObjectScrollListBase<FileSystemInfoWithNameOverride, DisplayFileButton> { } and public class LimitedTextScrollList : LimitedObjectScrollListBase<string, TextDisplay> {}
i know. i do that too
good idea
in my case, I have
public abstract FixedSpawnPointBase<T> : FixedSpawnPointBase {…}
public FixedSpawnPointSingle : FixedSpawnPointBase<TilePlacement> {…}
public FixedSpawnPointLine : FixedSpawnPointBase<TilePlacementContig> {…}
public FixedSpawnPointTilemap : FixedSpawnPointBase<TilePlacementContig> {…} ```
it's just a component that creates the line element instances for you. You just have to call public void SetList(List<TListElementType> fullList) and it does the instantiating for ya.
So I need to use a text file to save variables from a script that I modify during play mode so I can set them back in editor mode(theres hundreds of gameobjects with this script, so I cant just use playerprefs or something)
Is there a way to get some ID or something of the gameobject that contains the script whos variables I modified that I can use to find that gameobject again once I back out of play mode?
for reference, I have a non-generic base class underneath so I can GetComponent etc without knowing the generic form
without unboxing a fuckload of structs
I do recommend consider a similar structure
not sure if this guy will help when you need to go back, in the editor, and find em. but GO's DO have this member: https://docs.unity3d.com/ScriptReference/Object.GetInstanceID.html
right now, you’d probably need an interface to try to access everything independent of the generic. Such as clicking on element X. An abstract nongeneric class might help a bit
yeah I thought so, but I dont think theres a awy to find them by that ID unfortunately
can you give all the GO's unique names? If not.. perhaps you could store name + parent's name+ grandparents name.. etc...
Thanks @clever lagoon @hard viper for the answer
you can just register all of them with a system that can do the lookup by id for you
the names will not save if I do it in play mode, and since this is for something fo ruse by other people, I want to keep the changes to the hierarchy to a minimum
I could yeah!
Thanks @hard viper for the tip with Strings I heard its Bad practice I am a Junior Dev with 1 Year experience and trying to follow the Unity Path right now and just get some results and learn some techniques. I will ofc watch out for better practice in a Project where it matters.
I do indeed use interfaces alot..but on the lineElement, rather than the list as a whole: eg. /// <summary> /// Event triggered when the pointer exits an element in the list. /// The int parameter represents the index of the element in the full list. /// Note: The prefab used (TLineElementPreFabType) must implement the ITriggerOnHover interface for this event to work. /// </summary> public UnityEvent<int> onPointerEnterEvent { get; } = new UnityEvent<int>();
I just dont want to overengineer and do complicated stuff for the challenges and the videos flying them through as quick as possible while playing around with stuff
strings? I';d use an int for the "mark".