#archived-code-general
1 messages · Page 149 of 1
ah so raycasting it is
if this isn't a physics game I wonder what you want the normal for and if it can't be solved in a simpler way
its quite simple: thing moves around, hits some object and then has to randomly choose a new direction
I wanted to use the normal to define the random vector that changes its direction
That doesnt sound like a random vector then
well without a normal how does one define what directions are possible?
couldn't you just exclude the direction the object came from?
Why do we need collision normals
im not sure if I need them
You definitely dont
surely the object that is moving or something that is moving it knows what direction it was being moved in
Yea ontop of what praetor said, you also easily have the position of the object you hit. Using the position of the object, and/or the direction you're already moving this doesnt seem like a hard task
angle between 0 and pi radians
bit like diffuse lighting calculations, but random
since it is has a bit in common with diffuse lighting I wanted to find normals
Are u not able to use a collider? Like does this specifically HAVE to be a trigger?
not really but I was wondering if it was possible without 2 rigidbodies
since for the collisionenter you do need two rigidbodies
No u dont
really?
you need one dynamic body and two NON trigger colliders
let me try yeah one dynamic is necessary for all of these
you guys are completely right
I totally misread and misunderstood that entercollision function
thankss
So normals do seem to be the way to go right
https://unity.huh.how/info/collision-matrix these are what can collide
yea the unity docs do word that one poorly imo
fast array? interesting . . .
I need some help with this coroutine. It's intended to move things like doors, with physics. And it works fine except for the fact that the duration seems to be wrong.
Would greatly appreciate any help with this
because you threw an extra yield return null in there
so you're waiting an extra frame for no reason
can anyone help me with unity studio not showing errors ive followed all the !.ide links so please try to help me some other way
What are some good examples for methods?
fair enough
This launch pad is not adding an upwards force to my rigidbody when I step on it, I debugged it and it is detecting when I step on it. It just isn't making me launch into the air. https://hastebin.com/share/iloxukiwej.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Which part of this is the launch pad
OnCollisionEnter
I should probably organize the script better
but, i fixed the launch pad, now i just need to keep momentum when launching off it
Rb should just keep it by self. But also you should maybe change how you do the ramp
Shouldn't adding force just add to the current velocity/force of the GameObject?
OnCollisionStay you add force based on the current velocity but this might go wrong fast
How so?
Yeah, but for some reason, when i land on the launch pad from the ramp it doesnt keep momentum, it just launches me in the air.
Well you might start adding a ridiculous amount of velocity, the faster you are going, the more you add
If the user gets caught on any object, this will very quickly break
I would also probably have the jump pad apply velocity to the player instead of the player checking for a jump pad. At least this way your player script doesn't get clogged with
If(..compareTag())
For every interaction
Like this then? cs private void OnCollisionEnter(Collision other) { if (other.gameObject.CompareTag("Player")) { rb.AddForce(Vector3.up * jumpPadHeight, ForceMode.Impulse); } }
This is on the JumpPad script btw
For people stumbling on my message in the future. I ended up using a static class with the Lazy<T> solution with a property from here ("sixth version") and Resources.Load to get my ScriptableObject: https://csharpindepth.com/Articles/Singleton
I can't load the data async because when I call for it, I need it right away to initialize other data, and these configuration files must exist for the game to boot. I'll have to survive with hard coded string paths.
ouch
Well you would have to add the force to the player, not to the jump pad
Yeah, rb = accessPlayer.rb;
sorry, forgot to include that
If I have a prefab with a scriptable object asset attached to it, if I instantiate an instance of that prefab, do I get a unique instance of the scriptable object or is it just a reference?
f I have a prefab with a scriptable object asset attached to it
You don't, you have a prefab with a reference to the asset.
if I instantiate an instance of that prefab, do I get a unique instance of the scriptable object or is it just a reference?
Still a reference to the same asset
Can I optionally send out a parameter via an Event? Ie.
MyEvent(Var var)
ThingWhenMyEventRuns(Var var)
OtherThingWhenMyEventRuns()
I know about optional parameters but does that just work in events like the way I’m thinking
can anyone help me with unity studio not showing errors ive followed all the !.ide links so please try to help me some other way or explain me through it(edited)
Is it possible to use Rigidbody2D interpolation with a kinematic rigidbody?
Assuming you mean UnityEvent, yes you can:
public UnityEvent<int> MyIntEvent;
void Start() {
MyIntEvent.AddListener(HandleEvent);
}
void Update() {
MyIntEvent.Invoke(5);
}
void HandleEvent(int arg) {
Debug.Log("Number is " + arg);
}
You can also do the same with C# delegates
public System.Action<int> MyIntEvent;
void Start() {
MyIntEvent += HandleEvent;
}
void Update() {
MyIntEvent(5);
}
void HandleEvent(int arg) {
Debug.Log("Number is " + arg);
}
Sorry my question was phrased poorly, pre-coffee
Can I also have for example
void OtherHandleEvent() and still make it listen to the event? or do I need to have OtherHandleEvent(int arg) and just ignore the parameter im getting
I want to grab the parameter when it's needed but that isn't always
The handler needs to match the signature of the event, yeah. Typically I'd do something like:
public System.Action<int> MyIntEvent;
void Start() {
MyIntEvent += HandleEvent;
}
void Update() {
MyIntEvent(5);
}
void HandleEvent(int _) {
Debug.Log("Event was called");
}
Or if you want to future proof the API you can do something like:
struct EventInfo {
public int Number;
}
public System.Action<EventInfo> MyEvent;
void Start() {
MyIntEvent += HandleEvent;
}
void Update() {
MyIntEvent(new() {
Number = 5,
});
}
void HandleEvent(EventInfo _) {
Debug.Log("Event was called");
}
That way when you add more parameters you don't need to update the listeners
OnCollisionEnter etc work this way, giving you all the context you could need to handle the event, even if you don't use it.
Right fair fair. I was looking for a way to make it super generic but im probably overthinking it, heard chef
tyty
does nobody know how to help me
I would just ignore the parameter, it's not worth caring about
Other case u could probably make a new event without it
Yeah if I need to I'll probably go this route, Just didn't know if C# had a neat way of streamlining it 👍
https://youtu.be/kI6H3_Ry49k Try this video
Does anyone know how to use interpolation with kinematic rigidbody2d?
is it possible? The docs don't say
Has anyone been actively using naughty attributes to hide elements can tell me if it's possible to hide elements based on multiple enum conditions? There doesn't seem to be an overload for multiple conditions and attempting to change the enum into a bitfield doesn't seem to work either.
Using the flag attribute seems to work I think, but this then allows the editor to select multiple enums which is not something I want.
You can use HideIf
[HideIf("HideMyField")]
public int MyField;
bool HideMyField(int value) {
return (someEnum & (someFlag | someOtherFlag)) == 0;
}
Ah, ok maybe that's what I'm looking for. For scriptable objects, I guess that I would resolve that in onvalidate perhaps?
What do you mean?
NA calls it
Is there a nice function for me to use to run code when the relevant object is selected in the inspector? (Using [ExecuteInEditMode])
OnDrawGizmosSelected will work even without ExecuteInEditMode
If you want it to run only when inspector is drawing then you can use OnValidate or sometihng like:
[ExecuteInEditMode]
// ...
void Update() {
#if UNITY_EDITOR
if (UnityEditor.Selection.selectedGameObject == gameObject) {
// blah
}
#endif
Personally I use OnDrawGizmosSelected
where possible
Have to avoid OnDrawGizmosSelected because a lot of the time I have them disabled :/
Ah, yeah that seems to work once I fixed some of the nesting issues. Thanks ^^
Hi all, does anyone know how to access 2D lights via script in Unity 2021.3.26f1?
Just trying to change a light colour and it seems that the namespace using UnityEngine.Experimental.Rendering.Universal; is incorrect
I can access Light2DBase but it appears to have no light-related properties
Appears that Light2DBase is a 2D light, I can assign a reference to it and all
But you cannot change any light-related properties, which makes me wonder why it even exists
Going to try installing 28f1 to see if that's fixed it at all
I make a custom timeline playable and anything work fine on UnityEditor. Once I make a build on Android, all the function is not called and nothing happen! Does anyone knows why?
My cinemachine freelook camera has decent sensitivity when using the mouse, but with the gamepad joystick it's painfully slow and I can't seem to balance the two. It's either the mouse too sensitive and the joystick just fine, or the mouse is decent and the joystick too slow. Can someone help me?
for some reason my Cinemachine virtual camera wont move on the y axis, heres my code and camera
if you disable the script, can you rotate it manually via the inspector?
if not, its something related to your camera's settings
play around with them until you're able to change rotation.y via inspector, then re-enable the script
oh wow yeah disabled the script and it won't rotate i can only move it around
thought so. I'd guess it's the Hard Look At setting for Aim
it turned out to be the look at playerroot
Any good dependancy injection frameworks out there?
roll your own imo.. everything existing is super bloated
I have been looking as well, gotta try a few out tomorrow
How bloated is bloated, and in what way?
well, for starters, let's start with stating that a DI plugin should not need an installer 😛
Hm?
Zenject is bloated yeah but it works okay
Haven't tried VContainer yet
Others I know are quite dead
a DI system could be as simple as this:
Dictionary<Type, object> interfaceTypeToInjectedObjectMap; // Populate this somehow
void Awake() {
foreach (var obj in FindObjectsOfType<MonoBehaviour>(true)) { InjectRecursive(obj); }
void InjectRecursive(object obj) {
foreach (var fieldInfo in obj.GetType().GetFields(flags))) {
if (fieldInfo.HasAttribute<Inject>()) { fieldInfo.SetValue(obj, interfaceTypeToInjectedObjectMap[fieldInfo.FieldType]); }
else { InjectRecursive(fieldInfo.GetValue(obj); }
}
}
}
If you are gonna write one feel free to fork mine 😄 https://github.com/cathei/PinInject
ooh the string-based injection looks cool
I wish Unity would expose some event like UnityEngine.Object.OnAwake or smth :/
I am trying to make an Android build for my project, however it appears I am missing the necessary JDK, SDK, NDK files to build the project. I am working on an LTS release so its not as easy as adding them from the Unity Hub. How would I go about fixing this? Is there an option to add these when Installing the editor version, If I re-download and install this version again will that cause errors if i dont first uninstall?
Wondering if someone could help me solve a raycasting inconsistency issue. Currently, I'm checking for a surface with a certain layer above the player when its crouching. If the raycast hits a surface with that layer, the code will disable the crouch toggle input. Otherwise, it will enable the crouch toggle input.
Currently, it seems inconsistent by sometimes returning the correct value and other times returning the incorrect value. My code below is also in the fixed update method:
` Vector3 capsuleColliderCenterInWorldSpace = stateMachine.Player.ColliderUtility.CapsuleColliderData.Collider.bounds.center;
float halfColliderHeight = _colliderData.CapsuleColliderData.Collider.height / 2f;
capsuleColliderCenterInWorldSpace.y += halfColliderHeight;
Ray upwardsRayFromCapsuleTop = new Ray(capsuleColliderCenterInWorldSpace, Vector3.up);
Debug.DrawRay(capsuleColliderCenterInWorldSpace, Vector3.up, Color.red, 2f, false);
if (Physics.Raycast(upwardsRayFromCapsuleTop, out RaycastHit hit, _colliderData.SlopeData.FloatRayDistance, stateMachine.Player.LayerData.GroundLayer, QueryTriggerInteraction.Ignore))
{
_shouldToggleCrouch = false;
}
else
{
_shouldToggleCrouch = true;
}`
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Is stateMachine.Player.LayerData.GroundLayer a LayerMask?
Yes it is
Yeah making it inject before Awake is called is quite tedious :/
Maybe anyone could take a look at this problem?
https://discord.com/channels/489222168727519232/1128942517023416370
After download ASTC type image, creating actual image out of it provides image to be slided to one side and gives corner of pink pixels. I guess don't know something about loading image from bit array, so please help me.
Hey, is there any free asset that will find every unreferenced scripts to remove those annoying warnings?
or is there anything inbuilt
can you tell why this tells me there is behaviour missing? There is a script assigned to it and no console errors
Typically, the file name does not correspond to the class name or there are several MonoBehaviours in one file.
None
there is only one Monobehaviour
and class name is same as file
but hmm
look. this is disabled
since it is not unity webgl
is that the reason?
Yep
What should I do? Should I ignore ?
Probably want to add the editor define as well
It might result in the script not included in the build(not 100% sure about that, but should probably fix it regardless)
Ok, thanks!)
Change the pragma to be inside the MonoBehaviour, or even inside SafeTransferFrom, and the error will be fixed.
You're not using WebGL inside the editor so this won't work because of it
If you put it in the method, the Monobehaviour is still defined, and you can assign the serialized fields, but the method will not invoke
Pragma blocks are usually very small since each platform has a very specific use case where it's required, so the fact that a whole behaviour is left out is weird
Very clever, thanks! Let me try
Might want to remove that screenshot as it seems to contain some sensitive data(keys).😅
:d
Ah.. yeah
Thanks
and there are some like these:
with none. should I just remove them?
But there should be something attached
Those appear when you renamed the script outside the editor, or moved them somewhere else
And Unity has no clue where it is now
So you would need to figure out what it is
I doubt just removing it is not a good idea, you should make sure it was not used
I do not know the name of that script , have no idea.
Okay, thank you very much
!
facing this error while integrating firebaseWebGL in unity
not easy to help without sharing at least the script
This is probably faster to ask here instead of finding something online xD
i'm learning custom editors, but i have a problem with gameobject preview, what i'm doing is this:
gameObjectTemp = EditorGUILayout.ObjectField("Temporary GameObject", gameObjectTemp, typeof(GameObject), true) as GameObject;
if (gameObjectTemp != null)
{
if (gameObjectEditor == null)
{
gameObjectEditor = UnityEditor.Editor.CreateEditor(gameObjectTemp);
}
gameObjectEditor.OnPreviewGUI(new Rect(0, 0, 100, 100), GUIStyle.none);
}
DrawDefaultInspector();
the problem is certainly on the new Rect(...) but i'm not sure how to handle that.
Should ask in #↕️┃editor-extensions
People that do editor scripting will hang out there
opsi hadn't seen that channel before, thanks 😅
can someone help me here please?
Using the New Input System? You can add a processor on your joystick action to multiply the output vector by some value. Or in code, pre-multiply the vector with a constant before passing it to whatever script needs it
issue is on line 54. PostJSON is not working , i dont know why , i am seeking for help but didnot get till now. i imported firebasewebgl nicely and completely , i hope importing of package will not be a issue.
i also added the image of error that i am getting on browser because of i guess postJSON.
anyone know how to apply a material to unitys Terrain ? (with code)
Isnt that just Terrain.material or something similiar?
In any case the material would have to use a shader that supports splat maps (terrain layers) and possibly holes
nah its all good i found it
it was Terrain.MaterialTemplate
i was verry confused xD
Hello I have a button and in the inspector I want to add an onclick button to this function
public void Spawn(Spawnable spawnable)
{
...
}
}
public enum Spawnable
{
Wall,
Door,
Trap
}
But in the editor it doesn't show the Spawn function. How is this fixable?
Did you reference the instance in the scene?
yea
it shows the class just not the Spawn method
When I change the parameter the method takes to int it works so I'm assuming unity doesnt handle enum parameters? or is there some keyword to use for the enum
Try adding the [Serializable] attribute.
Relative to enum.
I did sadly it doesnt work
what does that mean btw
I found something on google now but it's kind of a weird solution
Structs and whatnot are not serializable unless explicit.
do you have any other ideas?
I'm not sure if it's possible - not on my workstation right now. Maybe have an enum field on the script with the function being referenced and set the enum value there - you would expose a function without a parameter this way instead.
eh whatever I'll take a string and parse it to the enum 😴 thank you tho
public void Spawn() => Spawn(_spawnable);```
Okay, I've been using Unity enough to call myself vaguely competent. However there is a subject I’ve had problems finding information for. And that’s saving the status of a scene. So you can a) save the game or b) leave and come back to that scene.
I’ve found tutorials and documentation on how to store basic information such as DontDestroyonLoad, Player Prefs and JSON etc. But not the best practices to store whatever is going on in the scene. Like objects that were spawned in (flying bullets and enemies etc), physics objects you’ve kicked around or simply if the doors are open or not. Is there any docs or tutorials on how to bundle that? Or is there a way to simply snapshot a scene I’m missing?
hi guys why it only prints orange when I call the function : ```CS
using WebSocketSharp;
using UnityEngine;
public class WSClient : MonoBehaviour
{
WebSocket ws;
void Start()
{
ws = new WebSocket("ws://localhost:8080");
ws.OnMessage += (sender, e) =>
{
Orange();
};
ws.Connect();
}
void Orange()
{
print("Orange");
print(Random.insideUnitCircle);
print("Apple");
}
}
Please help even chatgpt didn't help
Don't crosspost, and it's because the websocket callback runs in a different thread and errors halt the thread but don't show up in Unity console
UnityEvent is pain
I don't know why that would throw an error (maybe Random isn't thread safe? Or print isn't?) but that's the usual explanation
there isnt built in way
it boils down to assigning ids to objects and on save attributing data to that id
each case is different, if the object is already in the scene, it will spawn in its initial state, on top of it you deserialize the state you want
e.g. positions, existence
not present in scene, you spawn it
you have many ways to serialize scene state, applicable under different scenarios
Ugh. I feared as much.
you can try those solutions from asset store like EasySave
never used them cant vouch
I looked at Easysave. It didn't seem that useful. If they have a "save scene" option they can have my money. serializing everything in a scene that isn't static seems like a huge pain in the arse
if you just "save scene" what do you expect to be saved?
everything? references between objects? values in every field? how deep? materials/meshes as well?
do we save reference to original prefab?
Hello! So i am trying to make not exactly a game, but a game template so that I can create similar games, and i would like some help!
So basically, when the enemy uses a specific power, for a limited time until the attack animation connects, the player can use another power to interrupt the enemy attack! The damage tick will be an animation event, of course! Now, how should i go about making all this a bit procedural?
So basically what i want is to be able to drag and drop powers into the inspector windows in pairs of two with the type of interaction and the animations that change for both the player and the enemy and I would like some advice!
I'd like to mention that the Power and EnemyPower are two scriptable objects!
I have the following ideas:
make a power matching script that will have exactly what I said above, two lists of powers, each power of list one interacts with the power on the index as the second list, but for each interaction, i have to add two separate animations, one for the player and one for the enemy, and i can t seem to find a way to do that easily
I could make the enemy character have states instead and for each state there should be a power that interacts with that state. So for example the enemy is knocked down, I can give the enemy the knocked state and if the enemy is knocked, I can make the power in UI active! Same could be done when the enemy is attacking! So when the enemy attacks using a specific power, i can say the enemy is in "attack 3" state. But again, the issue is i would have to hard code all the interactions, which defeats the purpose of making it reusable!
I might be able to use a dictionary or go hard at it and make a visual nodes system from scratch if that will allow me to make things easier in the future!
I would like to know what would be your approach to this!
do we only save deltas? do we save all components?
what if the next game version has different component layout on prefabs
how do you map that? discard old components?
generalized one fits all solutions are not feasible
most common approach is serializing a very narrow, very specific set of runtime data, the smaller the better just exactly what is needed to restore the state of the game
scene here is irrelevant
Well is there a way to do part b, hop in and out of a scene and keep it loaded in memory? I want to go a minigame then come back to the main scene if possible. Before if I wanted to save I used basic save points
scene is just a container, what you want is to reason in terms of the state of the game
save point is a good example, it encapsulates the state of the game into a very simple value
you already used json.net?
no, player prefs so far.
any serialization library?
nope. Again I wanted a strarting point to tackle this. But it's so nebulios.
ok, imagine we have pong, we need to store positions of the ball and pads, caveat is we cant hardcode it, lets say there can be many balls and pads
in terms of unity a ball or a pad is a hierarchy of objects and components
we wont care for now how they are structured internally
we care how to identify them
we need a root component for which the save system will look for
lets say that we have an interface ISaveable which we add only to the root components that represent the entity
so we will have class Ball : ISaveable and class Pad : ISaveable
the system will loop through all game objects in the scene and look for that interface
if we find an object with it, its a root object, dont look deeper
we grabbed all objects in the scene with this interface, and we will assign ids to them
class SerializedEntity
{
public int id;
public string data;
}
here data will be our serialized json, this is very simplistic, as in reality you would use some sort of container like JObject
now to get the data we will in a loop invoke ISaveable.Save()
which returns a string
this is the most rudimentary way to save state
to load this state we will need more information, for example in case of dynamic objects like Pad and Ball we will need information on what to spawn
Yes but it's a starting point I get.
so what we can do is, if its a prefab, we can assign an id to the prefab, and then resolve which prefab was that this object was spawned from
unity doesnt give you any built in way to id a prefab, so we have to add for example a component PrefabID which we create
in it the id can be a Guid, int, string
class SerializedEntity
{
public int id;
public string sourcePrefab;
public string data;
}
but some objects may be in the scene from start
we also need a way for them to be identifiable, so they need some sort of class PersistentID : MonoBehaviour
now we have 2 types of objects those that already in scene and those that are not
class SerializedEntity
{
public int? runtimeID;
public int? persistentID;
public string sourcePrefab;
public string data;
}
if the entity has a persistent id, it already exists in the scene
if not, it was contructed at runtime
those cases only differ in that one will be spawned
after that the same routine will initialize them
foreach(var serializedEntity in save.entities)
{
GameObject go = null;
if(serializedEntity.persistentID.HasValue)
go = GetGameObjectWithPersistentID(serializedEntity.persistentID.Value);
else
{
go = Instantiate(PrefabsStore.GetById(serializedEntity.sourcePrefab);
}
var saveable = go.GetComponent<ISaveable>();
saveable.Load(serializedEntity.data);
}
and thats pretty much it, in a nutshell
That's perfect, thank you.
the runtime id is used to restore references between objects
which is also done in a separate phase, since first all objects have to be created, then you can do a second pass and resolve references
does the thread handle unity specific things
It's your code, does it?
should i move this to code advanced or another channel?
Idk if this is where to ask but Anyone have an idea on how to make it where if you tilt your phone the character moves like temple run
Like not exactly like temple run but if yk what I mean where you kinda use motion control
do you know what your phone uses when you tilt it?
🤔
I honestly don’t know or I don’t know what you mean pretty sure the first one
Hello!
I'm trying to learn how to use the advanced mesh API and everything works when I use floats but it stops working if I use any type of int (even though the numbers I use are integers). For example here, I'm trying to pass 2 integers to my shader using texcoords. Then I use this data to color the mesh (yes it's stupid but it's just an example, I'll do smarter things later 😅 ).
(The mesh I generate is a 10x10 square made of 100 1x1 squares)
When I use float2 for the texcoord, it works (the mesh is yellow so the shader indeed got 1 and 1) but when I use int2 like this, the square is black (so it would seem the shader gets 0 and 0).
I tried everything I could think of but nothing worked, it's always black 😦
Here is my code :
(I forgot the struct :
public struct Vertex
{
public Vector3 position;
public int2 texture;
}
```)
Interesting, when I try Debug.Log(mesh.uv[0].ToString());
It throws an error :
Unsupported conversion of vertex data (format 11 to 0, dimensions 2 to 2)
UnityEngine.Mesh:get_uv ()
And then it prints (0, 0)
And if I do the same with floats, the error isn't thrown and I get (1, 1).
But I have no idea what that error means and can't find anything about it 😢
Hey so I'm trying to simulate a little ecosystem with blobs (living creatures which I'm just representing with spheres for now) and little food shrubs. I basically want to spawn in an initial population of these blobs, as well as food, and then naturally grow more food over time and have the blobs walk around, search for food, eat food, etc. Later I plan to add genes etc so its sort of like a like natural selection sandbox. I'm using 3 scripts
Ecosystem Manager: https://hatebin.com/ccshtstqli
Blob Script: https://hatebin.com/jlikcreoil
Food Script: https://hatebin.com/jlikcreoil
When I try and run the program, the blobs and food spawn in as expected, however the logic in the blob script to find an available food source and path to it is not working.
See image. The error is "NullReferenceException: Object reference not set to an instance of an object
BlobBehaviour.Update () (at Assets/BlobBehaviour.cs:38)"
I'm not really certain what specific object reference is not instantiated or why this error would be caused. I've had a read through the docs and my syntax looks okay, but I've just come back to unity after a long break so it could be something stupid. Much appreciated.
You need to account for null entries in in_range_available_food
You're not checking for null, but because it's an array, there will be null slots if there are not 20 food objects in range
so this
foreach (GameObject food in in_range_available_food)
will check all 20 object references in the array even if none are initialised?
Would you expect foreach to automatically filter out null objects?
No, the array just holds the value. You need to check if those values are null or not . . .
If you are confused about the behaviour of foreach, I suggest reading documentation
Gotcha, thanks
yes
it checks everything, make sure it won't throw you any error
how do i make it so that my main menu will play music that will continue into other scenes without duplicating music in the main menu scene itself? basically, when i go back into the main menu from another scene, there are now two instances of the music object: one under dontdestroyonload and one in the actual scene. i only want the one in the dontdestroyonload
Small physics related problem: I upgraded a project to 2022.2.15. In this project I move objects based upon horizontal axis input. The objects have (kinematic) rigidbodies attached, and with Interpolate on. In older versions I could move the objects super smooth by calculating a new position and then setting the transform to that position, and only use the physics at certain points (I disable the kinematic property, etc). But, since upgrading, I cant move the object smoothly anymore; It's super jerky, and moves a unit per half second or something janky like that. It does move smoothly when I disable the interpolation though.. Why is that, even though the rigidbody is set to kinematic?
ddol
Something's changed with my project and any time I select a sprite and make no changes, and select something else, I get the "unapplied changes" popup. Any ideas?
public class DontDestroyOnLoad : MonoBehaviour
{
private void Awake() => DontDestroyOnLoad(gameObject);
}
@supple wagon
probably not code question #💻┃unity-talk
How do you manage events and be sure to unsubscribe them correctly or even unsubscribe and did not forget it? how do you validate?
because in big games, there are many events thrown in different situations. Every developer should care
I sub/unsub in OnEnable and OnDisable
yes, but do you have any mechanism to check it? or just when a bug appears, fix it
I have a pretty low bug incidence for this sort of thing, so I don't check it
(150k line codebase)
is your scene saved?
For example, some days ago, my colleague had forgotten to unsubscribe an event somewhere and after that, I found it. It is scary and bug prone.
One way in my mind is to reduce these situations. For example if a base class exists and it can be subscribe/unsubscribe just once inside itself instead of every children class handles it yourself
Another way to check by using IDE. I mean check references in that event but I do not know a way to group += operator and -= operator separately. They are listed all in one place.
Maybe, one way is to implement that event (add, remove blocks)
public event Action EventA{
add{}
remove{}
}
you probably cannot
public class BaseClass: MonoBehaviour{
//...
private void OnEnable()
{
_instance.EventB += OnRaised;
}
private void OnDisblae()
{
_instance.EventB -= OnRaised;
}
public virtual void OnRaised(){/**/}
}
what's that?
you just += in OnEnable and -= OnDisable
not "just once"
I mean just once subscribe and unsubscribe in base class
instead of children. In some situations, it works
I thought you mean subscribing to event without unsubscribing from
so that it's done automatically when you subscribe
For example my noob colleague had defined instance as a protected one and then listen to that event in every children class
noo
like you can then make virtual method and then override it in base class
I like this approach as a default strategy for my events.
public event Action EventA{
add{} // first unsubscribe then subscribe
remove{}
}
I can find references for add and remove separately as well.
@earnest gazelle
protected virtual void OnEnableBase()
{
OnEnable(); // call Unity Message
foo += Bla;
}
private override void OnEnableBase()
{
base();
bar += Nice
}
Hello, I've been following Game Programming Patterns on State machines, but I was having trouble what the point of the first "public DuckingState() : charge time(0) {}"
Here's the full small code block, what's the point of having this piece of code in there:
class DuckingState : public HeroineState
{
public:
DuckingState()
: chargeTime_(0)
{}
virtual void handleInput(Heroine& heroine, Input input) {
if (input == RELEASE_DOWN)
{
// Change to standing state...
heroine.setGraphics(IMAGE_STAND);
}
}
virtual void update(Heroine& heroine) {
chargeTime_++;
if (chargeTime_ > MAX_CHARGE)
{
heroine.superBomb();
}
}
private:
int chargeTime_;
};```
what language is it?
It's in C++
what server is it?
What do you mean?
where do you ask this question?
Why are you bringing C++ here?
I understand this is C++ in a C# server. I am asking to understand what this function serves so that I can implement the concept in C#
Looks like a constructor, but you're asking people who speak English about French
you can ask chatGPT to translate it into C#
not very reliable though
chatGPT is smart
nice
Thank you, I'll look further into that on how that translates
anyway.
Dont get ChatGPT to write code for u
It is dumb really in programming
I disagree
chatgpt is fine for debugging
not really
It can return just templates
no.
or error resolvement
has anyone ever asked this.
don't ask why I need this
I don't actually
At least in gpt 3.0, I have faced really bad experience about it
cuz you're not very very beginner
not uniquely unity, but this is the most active programming chat I know of.
Is there a difference between how structs and records are garbage collected/their cost? If records are a reference type, that means memory is allocated on the heap, right? And if value types are kept on the stack, that means there shouldn't be any garbage collection cost for value types, unless they store references to reference types, right?
That's correct, as structs are allocated on the stack, and said stack is dropped whenever execution exits the scope, structs do not need to be GC'd
storing references to reference types doesnt change how structs are handled, the condition for structs to be moved to heap, to be boxed is if you cast a struct to object and keep that reference out of the stack frame
so theoretically if I had a record and a struct that both stored 2 ints, the struct would be slightly less costly? Even if only miniscule?
meaning if you (int)(object)myInt there is a good chance compiler wont box
Yes
small reference type objects go to the small object heap
this is the same heap where strings go, it is optimized for fast and frequent gc
but yes it still will go to heap, and it wont have the same performance benefits structs provide
what makes a reference type small and what is a small heap?
heap is divided into small and large object heap
threshold is about 85kb afaik
the benefits structs provide if used correctly is that they are not affected by the issues objects in the heap do
first they are in a stack, its a linear area of memory, and there is no reference tracking, no garbage collection and minimum cache misses and memory roundtrips
because everything is allocated next to each other
with records as reference type, any allocation means searching for a free spot in memory, possibly heavily fragmented, then each dereferencing means reading a line which can potentially have absolutely nothing useful apart from the record itself
which means the bytes in the cache line are useless, it also means that the memory has to physically warm up a cell row, open/read/close it and all of that for a single object
all the meanwhile the cpu is waiting
so if having to optimize as MUCH as possible, in your opinion(s), would it be better to have a struct with a bool that says use this / don't use this, or a record that can be made null with a null check? Since storing a bool costs memory, but storing a record costs garbage collection time.
struct MyStruct {
int a;
int b;
bool valid; // true if usable
}
record MyRecord {
int a;
int b;
}
void MethodStruct(MyStruct ms) {
if(!ms.valid)
return;
// stuff
}
void MethodRecord(MyRecord mr) {
if(mr == null)
return;
}
a null check is dirt cheap, if its not null you are instantly dropping performance
again if you are microoptimizing dont do it
Are you targeting a smaller memory footprint (quantitative) or stack vs heap (qualitative)?
not targeting anything.
GC is usually the concern, if it matters. Where heap allocation is slower than stack allocation.
I'm not, I'm just wondering in general as I'm curious.
Well, you said you were optimizing. Those are two different things. Regardless of storing a bool or whatnot, it'd still be on heap - smaller though.
Thank you guys. I like that nullable struct suggestion, I think I'll start using that where applicable. I actually have a use case for it right now.
numerous times I have written out a function to do a specific thing, then decided to see what ChatGPT came up with as its own solution and it produced nearly identical code to what I had already written, its not too bad for very specific and very common problems many people need solved.
it starts to shit the bed when you want it to do something above a 2/10 on the esoteric scale tho
like if you ask it for a recursive function to invert a binary tree, no problemo
ask it to produce code for some newer library or API that isnt super popular and mainstream though? Pure gibberish
Well to some extend, sure it can write some small little codeblocks which if that doesnt work properly can easily be resolved by urself. But trying to have it write full one scripts have been pure gibberish from my experience
It's a text generator trying to write you convincing text. If you are convinced by it, then it has done its job. If you are at the point where you are able to debug whether it gave you valid logic or not, then you dont need it. Most people who use it arent at that stage
And if you arent able to debug what it gives, you shouldnt even use it
I saw that, but I'm not sure what that does. I think it's in C# 10.0 though, so I'd have to change the version which breaks the compatibility that unity has.
which actually makes me remember a question, do unity projects have to be CLS compliant?
Anyone know how to add animations to my code. I tried adding animations to my game but the character goes under the map all weird like and i dont know why?
I mean sometimes it does give separate options according to perhaps ur first version of the code
And? Hows that related to what I said
If you have to beg it to give out the right answer, you're either just using it for fun or are wasting your time
Delete this and stick to one channel ( #💻┃code-beginner )
How to post !code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Ah, guess it's a cross post.
I mean what?
If you need to google more information about this, it's useful to know that a record is just a class. Comparing struct vs record when it comes to how it's stored in memory is exactly the same for struct vs class.
Records are a language feature. The runtime doesn't differentiate them from classes.
😂 😂 😂 😂 😂 😂 😂
what a timer
yup
Hi, I read a book about C# recently ( It's C# Player's Guide if anyones wondering ) and want to get in depth with unity and I'd prefer more challenging and fundamental things. I already did the essentials pathway and started to junior programming but I'm not sure if I want to continue with it or not. I made it up to the plane challenge and it felt pretty basic. Do you recommend me to continue it, does it give a decent fundamental for to start with Unity? If you have any recommendations I'd like to hear them, if you don't recommend jr. programming pathway what to go with or if you recommend what to go with after that? Thanks.
I'd say to start making something that seems fun, and you will learn along the way
Hello, how to make value to be able to be changed just within script during runtime and not in the inspector?
don't serialize it. so either make it private or give it the NonSerialized attribute
or use a property which unity does not serialize anyway
"runtime"
it should be able to change just when not in play mode
I should be able to set it before game starts, not while game is running
then you need to explain that better next time. you did not specify that you'd like to set it in the inspector then not be able to change it via inspector, you just said you wanted a variable that could only be changed via script at runtime
but the answer is to use a property that you set from the value assigned to some field in the inspector. you can assign the property in Awake and just use the property
I think it does, no? Records are compared as equal if all their values are equal, not if the reference is equal. I can't imagine an override to the Equals method that could do that for any number of variables.
i don't really see the point in this requirement though. it's not like your players will be able to change the value in the inspector when they play the game
yeah, actually
also it seems like making properties for every isn't very good idea
@somber nacelle thank you
Take a look here. You can see here that a record generates a class with equality overrides that considers all the variables. The runtime doesn't need to be aware of records because the compiler generates all the code necessary. That makes it a language feature.
https://sharplab.io/#v2:D4AQzABATgpgxgeygEwgWQJ4CV5OQWACgBvIicicCAMwBsEBDAFwgDkBXAWwCMYoBuMhSogAjAAYIAFRgAPJoMIBfIA=
ah, that makes sense.
aight so, I have a 2d game that I am working with Tiled Editor to build the tiles, and I use SuperTiled2Unity to import it into the game which produces a Grid and whatnot.
I already have it properly setup so 1 grid square = 1 unity unit nice and clean.
What I wanna do is get a list of all the walkable positions of the grid (which should all be whole numbers), so I can do shortest path algos for movement from TileA to TileB
Thoughts on a clean way to, ideally, pre-process this at compile time?
I can generate a Polygon Collidor for the walkable area atm, or I can generate Edge Collidors for the same
For example right now I have this Collidor that has been auto generated
Guys I’m coding the save system for the items in my game, and the file saves correct, but when I try to save the list that holds the items in my game, it just says {} in the file,I don’t know what to do
have you made the variables serializable?
i see
Also, JsonUtility doesn't serialize bare collections without being wrapped in some struct or class
Ok
aye, arrays are a bit wonky too, there was a wrapper I found online for handling them
did I do this right?
#nullable enable
private Command? command;
#nullable restore
i'm curious why you would think using nullable reference types here is necessary
ICommand isn't a reference type, I forgot to change the name for the question :p (haven't gotten around to changing name yet, still working on it)
then you don't need the nullable directive
I get a warning, CS8632
that's regarding nullable reference types. what is Command
wait. I forgot to save the file :p oops.
Sorry for sending again it got barried by other text but Idk if this is where to ask but Anyone have an idea on how to make it where if you tilt your phone the character moves like temple run
Not exactly like temple run but if you tilt your phone you can move an object I have an idea to make a tennis game with it
But I can’t find much on it
Should be some kind of gyro input.
Alr thanks
Should be able to search now that you say that, didn’t really know what it was called
Thanks that looks exactly like what I need
why this object rotating when it needs to only change position
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.tag == "Player")
{
GameObject hedef = collision.gameObject;
agent.SetDestination(new Vector3(hedef.transform.position.x,hedef.transform.position.y,gameObject.transform.position.z));
print("degdi");
}
} this is the code
this one is I think a bit less advanced so I will post here:
It seems like my logic for collidor.ClosestPoint is being messed up due to local vs world positions, as the gameobject the collidor belongs to is a child of another object, and the parent is not at 0,0,0
if I have the parent at 0,0,0, my logic generates my waypoints correctly, as they use collidor.ClosestPoint to determine if the point is inside the collidor polygon or not, so I get the expected output (red lines are connections between points that are considered adjacent, and the points should all be inside the collidor)
but if I move the parent object over to (-0.5, 0.5, 0), the logic breaks down and Im guessing this has to do with local vs world positions
Hello i am making a top down shooter in unity3d, and i have a player that shoots bullets that ricochet off walls. i got all that to work but i want it to also destroy the bullet after ricocheting a certain number of times and i can't seem to get that to work
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "collision")
{
currentBounces++;
if(currentBounces >= maxBounce)
{
Destroy(gameObject);
}
}
}
Wouldnt you want to destroy collision.gameobject
Let's start with !code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
what's with that tag check? You should add logs to make sure that tag check is working (also using CompareTag is more efficient)
i used it to check if the bullet is colliding with walls and stuff
you should add logs to make sure that tag check is working
Yo guys, do u have any ideas why tiles from the scene are "above" in order than my ui element??
Here is video about what i mean
and here is code of my ui element:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIElement : MonoBehaviour
{
private GameController gameController;
[SerializeField] private Image image;
// Start is called before the first frame update
void Start()
{
gameController = GameController.Instance;
}
void OnMouseOver() {
gameController.IsUiClicked(true);
image.color = Color.red;
}
void OnMouseExit() {
gameController.IsUiClicked(false);
image.color = Color.white;
}
}
i added one to check how many times it bounces and it isn't showing anything so i guess it is indeed not working
Where'd you put it? Inside or outside of the if statement
inside the first if statement
Hard to say. Are you using physics raycaster to detect the tiles?(are they actually tilemap tiles?)
im using nothing to detect tiles and no, they are not tilemap tiles
thats why im confused, im not detecting tiles and still they are taking priority over ui
What are they then?
just normal gameobject prefabs
Take a screenshot of one of these normal GameObject prefabs inspector and a screenshot of the UI object inspector.
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("collision"))
{
currentBounces++;
if(currentBounces >= maxBounce)
{
Destroy(gameObject);
}
Debug.Log(currentBounces);
}
}
i changed it to comparetag
Box collider on ui..?🤔
you should 100% be using the event system interfaces like IPointerEnterHandler for your UI objects rather than using colliders. or even just an EventTrigger would still be better than colliders with OnMouseOver
yeah... i wanted to detect if user is clicking ui - if yes then do not call tile methods
i will check those
thanks for help ❤️ ❤️
Hey idk if youd know but Can I use unity remote 5 without using a USB to connect my iPhone? sorry to bother
I do t think so.
ok IPinterHandler works fine, thank you @cosmic rain and @somber nacelle im your debtor 🤝
Does anyone know why the cursor disappears after loading a new scene? It's not a huge deal because it shows up when you move the mouse, but it's still annoying. Thanks for any info.
you probably have something like Cursor.visible = false; somewhere in your code. Use Ctrl+Shift+F in your IDE to find out where it is
I checked but I don't. Thanks though. But...hmmmmm....I do have a touch asset that I installed, I'll need to see if it's interfering.
interesting.. didn't know there were other ways to hide the cursor
did you make sure to scan the entire solution when searching? (including packages etc)
it is likely that the touch asset is interfering, but wouldn't make sense to use lower-level API than Unity's Cursor.visible to hide it :/
Oh, somehow I missed the Cursor state in the touch asset! I don't think I used Ctrl Shift F initially when searching for it. (I don't know what I used.) Thank you!!!
You need to log outside the if statement and log the tag
Might buy a usb hub since that’s the next thing in line to do. A post from a year ago says there’s no way completely wirelessly and my problem is an error about power surge from usb. Tried all trouble shooting and nothing worked. Unless there’s been an update. Thanks for the help
the bullet is colliding with the wall and i have the tags set up correctly, but i guess when it's colliding with the wall the collision.gameObject.CompareTag isnt working. i put the debug in update and the currentBounces amount is always 0 even when it bounces off the wall
Might be worth logging what the tag collision has before that if statement to see if the right object is being hit
Why is so much Y velocity being applied when clearlink is called? ``` private void UpdateLink()
{
Vector2 playerPosition = player.position;
lineRenderer.SetPosition(0, playerPosition);
if (targetPosition != Vector2.zero)
{
Vector2 direction = targetPosition - playerPosition;
Vector2 force = direction.normalized * grappleForce * currentMoveSpeed;
// Calculate velocity manually
velocity = (playerPosition - previousPosition) / Time.deltaTime;
previousPosition = playerPosition;
player.GetComponent<Rigidbody2D>().MovePosition(playerPosition + force * Time.deltaTime);
// Increase move speed for the next frame
currentMoveSpeed += moveSpeedMultiplier;
currentMoveSpeed = Mathf.Clamp(currentMoveSpeed, 0f, maxMoveSpeed);
// Debug.Log("Move Speed: " + currentMoveSpeed);
}
}
private void ClearLink()
{
lineRenderer.SetPosition(0, Vector3.zero);
lineRenderer.SetPosition(1, Vector3.zero);
lineRenderer.startColor = Color.clear;
lineRenderer.endColor = Color.clear;
targetPosition = Vector2.zero;
currentMoveSpeed = initialMoveSpeed;
Debug.Log("Velocity: " + velocity);
player.GetComponent<Rigidbody2D>().velocity = velocity;
velocity = Vector2.zero;
}```
np
PlayerInput: https://gdl.space/kiyedepevu.cs
SelectableUnit: https://gdl.space/mevugupage.cs
SelectionManager:https://gdl.space/jezekixexi.cs
Please help, I am trying to assign commands to those 2 objects, there but they just dont want to do it. first I am just playing with the move command and they just go flying off, then I try to use the Patrol command but they simply will not obey, please help me. Thank you so much already ❤️
seems like physics don't go well with your game. Your objects have dynamic rigidbodies, right?
Yes dynamic
the commands are working fine. it's the physics part that's causing them to fly off (because of collision between dynamic rigidbodies)
you could disable collision between those layers to start with, but I think the physics need to go completely, assuming the game's kind of RTS
so, I'm at a bit of a crossroads in this project... my game world is not appropriate for standard rigidbody physics and I long ago removed all rigidbodies and implemented my own physics, but now I really want to add some convex mesh colliders... my choices are go back and add isKinematic rigidbodies to everything just so I can detect trigger overlap - not even real collisions - or implement my own convex mesh colliders, which seems like a fair bit of work...
so im wondering what sort of overheard isKinematic rigidbodies carry? is it worth adding 1000s of them just to access isTrigger collider meshes? (99.9% of collisions are already culled automatically by my system, using something like an octree, and also they'd first have to pass through the existing simple sphere collision to even be tested) Or, is there maybe a 3rd party collision asset available that allows collision detection without rigidbodies?
Hello, I just wonder if it's even possible to pass value in UnityEngine.RangeAttribute ?
[SerializeField] [Range(min, max)] private int foo = 1;
What are min and max?
Const floats should work there at least
yes, thanks, const float does work
why I cannot serialize const field?
is it always so?
Yes, wouldnt make sense to serialize it since a const (constant) value cannot change
think it's done at compilement time so you couldn't seralize it?
I see, thanks
but why can I use const fields that are below my fields with RangeAttribute?
usually when you do serialize data, it's done after compilement and the object is created
but at that time you couldnt change the const field
but what's the difference between const and readonly then?
oh yeah can you serialize readonly fields
ah, right you can set the object data variables, but only through the constructor
no, I cannot
const need to be defined at the time of assignment, while readonly field can be defined at runtime
yeah true
even though it cannot be selialized 🤔
that was a question, but I would assume they would be serializable. /shrug
oh, I thought that wasn't a question
I'm trying to make this EnemyAI and theres one issue. It works perfectly fine until one time. The enemy is able to chase the player, but after the player is out of the enemy sight range, the Patrolling() method is called. However, the enemy is no longer following the waypoints. Any solutions would be helpful.
I have 2 scripts that's running. the EnemyAI script for the enemy and the Waypoints script for the waypoints.
I want to make is so that when the player is out of the enemy sight range, it teleports back to the waypoint
The enemy does teleport back to the waypoint but it doesn't seem to loop. It just stops after moving for a while. I wonder what I did wrong in the code?
Also don't mind the animations. I just didn't code them yet.
const you can effectively treat as having a straight up string replacement performed on it at compiletime, like as if your source code itself got the value substituted in as compilation happens, making it immutable and locked in.
IE
const int Foo = 1;
var Bar = Foo;
will effectively compile to
var Bar = 1;
readonly on the other hand means it cant be modified once set, but its still dynamic in terms of setting.
For example you can have a readonly field on your class, when you make a new copy of the class it will get a new copy of that field, but you cant change the value of that field, its read only. The big thing is readonly has an improvement in terms of memory and passing a reference to it into a function
Has anyone else encountered infinite Application.UpdateScene loading, whenever attempting to create a new script? I'm guessing it might have something to do with ECS, since it started to happen after installing the packages. And before anyone asks, there're no dead loops. This is in a new scene, with nothing but a directional light, global volume, and main camera.
don't forget, you can change a readonly field using a class ctor . . .
Constants must have a value that does not need to be calculated at runtime, such as numbers, strings, like that. Readonly fields and properties are calculated at runtime and has a larger range of possible values. These can also be assigned through a constructor or class initializer. A constant does have the ability to be used in more things, such as attributes
Constants are always static, readonly can be instanced
I see, thank you
thank you too, I haven't mentioned your message before
is it possible to make coroutine that returns Vector2?
oh.
var foo = GetCaretPosition();
private IEnumerator GetCaretPosition()
{
yield return Vector2.zero;
}
that won't work for sure
I am trying to make a score penalty when the player fails, but the penalty is not being applied?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameOver : MonoBehaviour
{
public Transform player;
public Rigidbody playerRigidbody;
public int minimumYLevel;
private float initialX;
private float initialY;
private float initialZ;
Score gameControllerScore;
[SerializeField] GameObject gameController;
// Start is called before the first frame update
void Start()
{
gameControllerScore = gameController.GetComponent<Score>();
initialX = player.position.x;
initialY = player.position.y;
initialZ = player.position.z;
}
public void ResetGame() {
player.transform.SetPositionAndRotation(new Vector3(initialX, initialY, initialZ), player.transform.rotation);
playerRigidbody.velocity = new Vector3(0,0,0);
playerRigidbody.angularVelocity = new Vector3(0,0,0);
gameControllerScore.ScorePenalty += 10;
// Is meant to apply the penalty here ^^
}
// Update is called once per frame
void Update()
{
if (player.position.y + minimumYLevel < initialY) {
ResetGame();
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class Score : MonoBehaviour
{
public Transform player;
public TextMeshProUGUI scoreText;
// Update is called once per frame
public int ScorePenalty = 45;
void Update()
{
scoreText.text = (player.position.z + ScorePenalty).ToString("0");
}
}
Why isnt it adding to the ScorePenalty?
Shouldn't ScorePenalty be a negative number?
uh it should be
gameControllerScore.ScorePenalty -= 10;
yes, but it should start at 45
still isnt changing yet either way
I'm assuming it is updating scoreText.text with a value equal to player.position.z is that correct?
right.
scoreText.text = (player.position.z + ScorePenalty).ToString("0");
Have you tried hardcoding a value for ScorePenalty? Something like
scoreText.text = (player.position.z - 50).ToString("0");
well, the 45 is working. just not the 10 being subtracted on death.
Not sure how that would solve the issue yeah, it needs to be dynamic
Just general debugging to see where things are going wrong
Make sure the code that adds some penalty runs, and that it's referring to the right script
what do you mean?
Also I'm assuming you aren't getting any errors, especially a NullReferenceException
That would have been nice to mention with your original question
I think it's a part of my movement though, I'm not entirely sure
i haven't had a good look because my console is being spammed
Oh bb no, try keep a clean console for your own sake, will make like easier
These errors will stop all the code from running, you might not be even reaching the point where it adds the penalty
ohh
yeah there is a null reference in GameOver.cs
NullReferenceException: Object reference not set to an instance of an object
GameOver.ResetGame () (at Assets/Scripts/GameOver.cs:30)
GameOver.Update () (at Assets/Scripts/GameOver.cs:37)
And as for the "make sure the code that adds the penalty runs", that can be done by Debug.Log
Okay the error happens on GameOver, line 30
(GameOver.cs:30)
which is this
gameControllerScore.ScorePenalty += 10;
So gameControllerScore did not have a value
what would be a clear way to display these assets as temp
Where do you put a value into this variable?
Yes
But not like that
Okay so, the object that's in gameController variable didn't have a Score script on it
You don't want to use an IEnunerator, you want to go a step above and use an IEnumerable. These allow a generic, which is a Vector2 in this case
Note you cannot use these in a coroutine
omg I forgot to move it
oh no I did move it
but I was in play mode
omg
that fixed it
Now you know how to debug a NullReferenceException! Extract the line number from the error, look there what could not have a value, and see where you've put a value into it
coroutine doesnt return anything to you it returns the yield instruction object to unity
you are not calling this coroutine
I feel like null has something to do with 90% of my errors
yes, it's IEnumerable<Vector2>, but it returns "collection" of Vector2
what.
Same, that's why you got to master the art of solving them
yes, I don't know how else to call it, just understand it as you wish
There's no point in using GetComponent here at all, just serialize the gameControllerScore field and drag the object there directly
It's a collection when you enumerate it, before that there is no collection
Calling it wont make a collection yet
That's why you cannot assign an IEnumerable to an array without calling ToArray on it
Trying to think of a way I can mark a mesh as temporary in our pipeline.
I have a custom scene builder (so I can merge scenes in source control) but im not entirely sure how I want to visualize it in the editor that a mesh is temporary and needs to be replaced. If a mesh is temporary or not is flagged in the scene builder metadata.
Any suggestions?
they should just remove null tbh
IEnumerable is not a collection its an interface
that's why I have written it within "
i can make a class with no fields storing nothing and it would be ienumerable
yes, how do I make it to return not "several Vector2s"
just one
it's impossible I guess
this smells hard of xy issue, what are you trying to achieve
Haha that would add some more safety yeah.
Some languages have an Option Type, where nulls don't exist and it's all "I may have a value, or not", and you explicitly get the value
C# has that, but for structs only, called Nullable
yeah, actually I have asked this 1 hour before and then understood that I don't really have to use coroutine there, so I just made is Vector2 return type
I though that I should have used yield return new WaitUntil(() => ...) and then return Vector2
you cant do that with a coroutine, you cant return anything
coroutine is a generated class
its a separate object
its out of your control
or just force the user to make the varaible with a value
returning Vector2 won't throw any error, it just doesn't make sense
you understand what happens when you start a coroutine?
By not making an IEnumerable and just returning it from a normal method? 🤔
I think I do, maybe I don't know smth you want me to tell though
Or you yield one entry and the break from the method
what.?
when you start a coroutine, a class is generated by compiler
then an instance of that class is created
it is passed to StartCoroutine() where unity calls MoveNext on it
and unity expects a YieldInstruction to be in current
if its anything else
unity will simply treat it as a null, and await 1 frame
thats it, there is no way for you to use returns there, only thing you can do is assigning by reference
ie
Unity just hijacks the features
IEnumerator foo()
{
this.myVector2 = ...
}
yes, I can just assign smth in local coroutine and then return in method
You use an enumerable to enumerate values and create a collection, you cannot return a single result. If you only want one, you might as well just make a regular method
I see
It makes no sense because there is no yielding with a single result
If you need to wait for some time, but still be able to return a value, then you need async methods. With UniTask for Unity
Or regular Tasks
private Vector2 Foo()
{
Vector2 nice;
StartCoroutine(Bar());
IEnumerator Bar()
{
nice = default;
yield break;
}
return nice;
}
anyway I think it won't work with yield return null
What will this method return?
private Vector2 Foo()
{
Vector2 nice = default;
StartCoroutine(Bar());
IEnumerator Bar()
{
yield return null;
nice = Vector2.up;
}
return nice;
}
default
nice.
The coroutine did not have the time to run the assignment before execution reached the return
you cant await asynchronous results in a synchronous call chain
be it coroutines or async
you want that, you have to chain async
so Foo has to be a coroutine as well
that can await other coroutine
will this code throw compile errors in normal c#?
this is normal c#
nothing abnormal
the only error you would get is StartCoroutine is not defined
thats vector2 in normal c# , it doesn't have up property
Yup from System.Numerics
do I need to use it?
The implementation is open sourced, you couldn't
how do I start coroutine then?
he's making a joke cuz you said sue, not use
start coroutine outside of unity?
yes.
there are no coroutines out of unity
coroutine is a unity concept
you can use async
or implement your own coroutines
to educate yourself on how they are implemented
Tasks 😛
I see
Could make a method stub that takes in an IEnumerator, but it wouldn't do anything because it requires the whole engine below
not the most interesting thing to do
public async Task DoSomeWork()
do I yield return there?
its pretty interesting if you are interested in how things work
you can do things like Task.Delay etc.
yeah, just if you are good enough in programming
WaitUntil?
nevermind, it's while loop anyway
on the contrary
that would just be await prob
you get good by doing stuff like this
probably
thank you all for your help 🤯
Trying to think of a way I can mark a mesh as temporary in our pipeline.
I have a custom scene builder (so I can merge scenes in source control) but im not entirely sure how I want to visualize it in the editor that a mesh is temporary and needs to be replaced. If a mesh is temporary or not is flagged in the scene builder metadata.
Any suggestions?
public async Task SomeTask(){
await SomeTaskToWaitUntil();
// continue after wait
}```
in technical terms what is temporary?
just a placeholder?
or hideflags?
or serialized in place?
placeholder meshes that should be removed and replaced for the final result
replacement as in by artists, or some automation?
same applies for meshes that are under revision and marked for replacement
manually, by artst
so flagging the asset itself would suffice?
yes, since the dimensions of the asset will remain consistent but the mesh itself needs to be replaced.
@slender depot ?
editor only, but you are doing validation during build i assume
why the x emoji @slender depot
precisely, I have a build script setup in our SRP to make sure I check for meshes flagged for replacement.
but right now, its a MB with a bool flag xd
really?
MB in a prefab?
aye
yeah why x ?
and on top of that you can extend editor to make it feel native
for example the hierarchy can render an icon on prefabs that require replacement
and the name of the file render in some other color
oho, interesting
and a simple hotkey to toggle label
how do you manipulate the hierarchy view and add to that tho?
Im not familiar with that
the only downside, which is arguably not a downside, is that your source control can get spammy with labels
you inject your callback into ProjectWindow.onHierarchyGUI or something similar
let me check
oh not hierarchy, i meant project
but same goes for hierarchy
there is also a callback afaik
just found this too https://tech.innogames.com/customizing-unitys-project-window/
oh I see
hmm
basically just using labels can get you very far
drawing a red rectangle on the prefab is enough
doesnt need to be complicated
I wonder if I can make that searchable in the project search bar,
like "show all flagged assets" or if I need a custom window for that
you can
string assemblypath = UnityEditorInternal.InternalEditorUtility.GetEditorAssemblyPath();
var assembly = System.Reflection.Assembly.LoadFrom(assemblypath);
projectBrowserType = assembly.GetType("UnityEditor.ProjectBrowser");
lastInteractedProjectBrowser = projectBrowserType.GetField("s_LastInteractedProjectBrowser");
MethodInfo setSearchType = projectBrowserType.GetMethod("SetSearch", new[] { typeof(string) });
private static void SetSearch(string filter)
{
setSearchType.Invoke(getLastProjectBrowser(), new object[] { filter });
}
where filter is the l:Label
reflection saves the day, despite unity's best attempts to hide the relevant apis
in recent versions there may be a native way, i would check it
I'll have to look into that, this looks like it should exist
otherwise, I'll fall back on this I think
the shit you can pull with reflection sometimes just really surprises me
and most of the time I wonder why its not exposed in the first place so we can more easily extend things
Thank you. I will look into it
thx
@ashen yoke are those asset flags visible somewhere in the editor?
bottom of the inspector
ah
you can manually type them in
yep
now I just need to get the rects to work properly so they dont take up the entire space
cuz I may have fucked up lol
that works, right now im drawing a small rect but that seems more user-friendly
this is my banana item spawn script: https://gdl.space/qezunohuri.cpp
this is my player actions script: https://gdl.space/mokiwohifo.cs
In my player action script, when the player looks at a banana object with the name "Banana" a text is suppose to pop up. If the player presses "e" while looking at the banana then the banana object is suppose to get destroyed. When I look at the banana (in game) no text pops up, and my debug.log statement doesn't show up in the console. I'm wondering what I'm doing wrong in my Physics.Raycast() code for this to happen.
use debugger
put breakpoint at 54, and start the debugger while looking at the banana
Why don't you follow the debugging steps suggested to you? There's no magic here, you need to log things and figure out WHY it's not working
so a trycatch block costs about 30% more than direct call
maybe less, about 20%
which is great
I put a breakpoint at 54 then tried to run the game but it wouldn't load
then I stopped debugging and got no errors
wouldnt load?
ok you have a breakpoint set at 54
game is running
aim at the banana and switch to vs
make sure the aim is on the banana
the game wont run when I start debugging in vs
then in vs click attach to unity
oh do I run the game first then debug
most likely it starts, you just instantly hit the breakpoint
because your breakpoint is in update
that wouldn't make sense though the banana's spawn point is not close to my player's spawn point
yes
and you do that exactly because your code is in update, so you have to setup first the scenario in which when the breakpoint is hit, it carries useful information to you
alternatively you can just position the banana right in front of the camera
and start from there
then you are guaranteed to get the info on the first update
you are not supposed to "get errors"
you are supposed to look into values
when you hit a breakpoint you can inspect the values of any variable
just by hovering over it
which helps you understand what is going on at that exact moment
for my hitBanana it says "Object reference not set to an instance of an object"
then hitBanana.collider = null because of this
So I have another pattern advice question. I have a series of classes inheriting from a base module interface. I need a large number of classes to do things like targeting, movement, firing, ect for these module classes. Would you recommend:, 1 : Just a bunch of separate classes with static methods and just deal with passing around a lot of parameters, 2: Build the class out of partials 3: Shove all the method calls into a base abstract class instead of an interface, or 4. Use dependency injection?
Dependeny injection almost feels a bit heavy handed. Abstract doesn't really solve the seperation issue. Partials just seem kind of gross. Separate classes is ok, but I am passing around a lot of the same variables over and over, so making changes might be a bit more difficult.
You've already partially implemented a component system. You've already decoupled using the Interface. All you really need at this point is a system for your components to register/deregister with an object that tracks and manages your components. There's a variety of strategies you can use to pass information to your components from there which really depends on your needs
For example, you could have your components subscribe to certain data when they register
@rugged goblet This is more about handling a large number of "helper" classes that are mainly used to extend the module classes. like a weapon class needs to, get targets in range, validate targets in range, get a predicted location transform on it's target, calculate a torque value for rotation of a turret... ect. I might just be overthinking it and should probably just deal with sending parameters to each.
Yeah unless you're finding yourself passing a ton of parameters just pass parameters
Fair enough, thanks
@wheat relic Maybe you are toggling CanMove to false somewhere?
To be a little more specific, creating any external source of data that your methods have to access couples them. Passing the data as parameters means that you're much less likely to need to change your utility methods when other code changes
Hey, I tried to make a custom editor to change the values of an array, but for some reason when I close the inspector and reopen it, the values are reset, any idea why this might be happening?
can move never goes to false
@wheat relic Ok then what about isgrounded?
ty I'll ask there
thats a character controller component, i dont see a bool for it
Maybe log t he state of that value when you are reproducing the issue?
Maybe it flips to false when you stand still for some reason?
do i put that in the update?
this is the jump right?
if(Input.GetButton("Jump") && canMove && characterController.isGrounded)
{
chargedPower += Time.deltaTime;
}
no thats the charge up
basically how it works is, you hold down space to charge up the jump power
if (Input.GetButtonUp("Jump") && canMove && characterController.isGrounded)
{
moveDirection.y = chargedPower * jumpPower;
chargedPower = 0f;
}
use your own grounded check. the isGrounded property on CharacterController comes with a lot of caveats and isn't really great.
I would do something like this
if (Input.GetButtonUp("Jump"))
{
Debug.Log(canMove.Tostring());
Debug.Log(characterController.isGrounded.ToString())
if(canMove && characterController.isGrounded)
{
moveDirection.y = chargedPower * jumpPower;
//chargedPower = 0f;
}
Not sure if it's syntactically correct, but that would log the values when you hit the jump button without changing the behavior
Yeah, wasn't sure on that
you should add labels to it though
otherwise you're just going to get a bunch of random true/falses in the log and not know what is what
Debug.Log($"Can move: {canMove}, grounded: {characterController.isGrounded}");```
why dont folks just use the debugger
what is necessary then
i just wanna jump 😭
I recommend something more like this
already recommended a fix. Switch to your own grounded check.
You would think Unity would make their own save system be able to use Vector3 struct inside regular POCO for Cloud Saving..
Why unity... why.........makes no sense
ffs
what is "their own save system"?
so this happens when i move and am able to jump
when i stand still i cant jump and nothing shows up in console
Use the debugger
making a tutorial on it
apparently it doesn't like Vector3s
yes that's the point
we know isGrounded is false then
we have learned what we wanted to learn
Only when I have Vector3 in one of the POCO classes
What value is chargedPower when your standing still?
yes, as expected from CC.isGrounded
0 but it goes up as i hold down space
"unknown error " lmao
just say invalid serializable data or sum...wtf unity
is there a way to access cc is grounded?
DateTime scruct actually serializes properly for it, can you believe this shit.. must be an oversight.
it says "The Cloud Save editor accepts JSON Data Types. You must provide values that adhere to the formatting rules of JSON Data Types." but gives no explanation about what that actually means
What do you think this is?
no bools
ignore the inspector
doens't matter
Debug.Log is showing it
if you print it OUTSIDE the if statement you can see it always
but there's no need, we already know it's false
so its just competely unreliable and arbitrary in its ability to notice if im grounded or not
it's reliable if you understand how it works
but I already. recommended several times to you
don't use it
maybe it needs to be inside another struct?
literally they made DateTime work so I'm guessing this is WebStandard JSON serializable stuff ?
this one works
[Serializable]
public struct SomeOtherData
{
public string Cool;
public float Time;
public DateTime RegisteredTime;
}```
```cs
public class GameSaveData
{
public int Score;
public float XLocation;
public float YLocation;
public Vector3 Location;
}
this only works when i take out Location's Vector3
Weird..
use your own grounded check
idno how but ill try
I guess DateTime good, Vector3 Bad 😦 oh well
Vector3 isn't marked with the Serializable attribute and is not serializable by most serializers
one of those weird Unity inconsistencies ig..
yeah you would think they would make it somehow work with their own cloud save but oh well
back to making struct for v3 it is
the feature is too cool to ignore..
I don't know why they haven't just marked it as serializable but I assume there's some reason
so strange right?
You could look up some unity c# examples of a custom character using rigidbody, they often use their own ground check, in general you would want to use the Physics class, there are many ways you could handle a ground check with that class, my personal favorite is Physics.SphereCastNonAlloc but there are other options as well - and if you optionally use a layer mask, you can have more control over what is considered a "ground" as well
thanks ill check that stuff out
actually i need the cc in order for the code to work....
shieeeeeeeesh
only because your script says [RequireComponent(typeof(CharacterController))] but yes obviously THIS script depends on it because it uses it everywhere
they weren't saying to remove it and use THIS script
it'd be a completely different script to use a Rigidbody
not so obvious to me obviously
Yes, Rigidbody and CharacterController are 2 different components and ways of handling custom characters, I was only suggesting to use the logic that Rigidbody characters use for ground check (the Physics class), which shouldnt require you to use a Rigidbody component, so you can keep your CharacterController if you prefer to use that
that's not a code question, delete and ask in #💻┃unity-talk
how effective are structs when it comes to memory usage?
i want to use them to store tile data on a tile map and my first thought is no good
would have been a list of lists with a int[,] but i already know thats bad, so trying to find another better way before coding
Hello all, im running into many problems in the forseeable future with my platforming game. I was wondering if anyone wants to hop in a call or chat to talk about procedural generation in 2d platformer games, and answer some of my questions?
struct are generally considered faster / less memory usage. They live on the Stack
like other value types.
Stack is faster cause its data is added and removed in a last-in-first-out manner, heap uses Pointers
If I'm looping through a list of transforms, is there a risk that collection changing while I'm looping through? Or, due to the nature of Unity's single threading, that shouldn't ever happen?
so if i had something like,
public enum LayerType
{
Floor,
Wall,
FunctionTile,
Decor
}
public struct Tile
{
public int x;
public int y;
public int id;
public LayerType layer;
public Tile(int x, int y, int id, LayerType layer)
{
this.x = x;
this.y = y;
this.id = id;
this.layer = layer;
}
}
that would be waaaaaaay better than a List<List<int[,]>>?
yea
at least imo
okay, thanks
and to clarify. structs are like little storage boxes you can make with set vars you can write to and they just float in the back of the game?
ive never used them before
Its possible that an object referenced in the collection being destroyed could leave that index as null, so if your unsure if the collection will remain consistent you could add a null check, though the case may depend on which frame (in relation to the loop) this happens, AFAIK
How do I make it so EditorGuiLayout Fields trigger "OnValidate"?
structs are data containers like classes but they are value type instead of reference types
okay i see
quick question: whats the difference between using interfaces and abstract classes?
i got a script from a youtuber, i set it up all correctly but it shows me this error:
the line
and the properties
I think its that abstract classes can have logic, while interfaces cannot.
please help
if it was just that, then interfaces would not exist, so i assume abstract classes can have logic, but at the cost of performance (which interfaces dont have)
did u screen this during runtime?
Im pretty sure thats it though, interfaces are like a cookie cutter
ok...
did you reference it through script or inspector?
transform.parent is actually the only thing on that line that can cause that error
your problem is your object just doesn't have a parent
wdym
transform.parent returns null if your object doesn't have a parent
so you're trying to do null.up
which is an error
in hierarchy you have to drag the scriptholder object on another object
this scerenshot shows that it doesn't have one
PulseTurret has no parent
(or if it does we can't see it from this screenshot because you cut it off)
scroll a little up and screenshot
wait, i need to make an empty gameobject with the script and make PulseTurret a child?
or fix your code
why are you writing transform.parent.up if it is not expected to have a parent
as the youtuber said most likely
yep no parent
yep it has no parent
try dragging the pulseturret on MainBody, i assume the spider has to hold the turret?
uhhh
or just go back to your tutorial and make sure you did things properly
I wouldn't start randomly dragging stuff around
idk why but i would
send us video link
here's the video btwhttps://www.youtube.com/watch?v=swYBGqXtHEY&t=1s
Sources: https://github.com/lchaumartin/SpiderProceduralAnimation/tree/FirstVideo
Music: https://youtu.be/4yEbXdevEYM
The spiders I used:
https://assetstore.unity.com/packages/3d/characters/robots/spider-orange-181154
https://assetstore.unity.com/packages/3d/characters/animals/insects/spider-green-11869
🎤 Discord: https://discord.gg/kYwzdvAt8q...
oooooooh
i saw it
one sec
cmon i did it right
no
you still have the script on an object that doesn't have a parent
oh
can u send a little more of the code
nvm
wtf is happening
See how in the video that script is on an object that is a child of the root object?
its rotating up and down in the z axis
this is the code from the video (found on description github)