#archived-code-general

1 messages · Page 149 of 1

leaden ice
#

another rigidbody sounds very complex

timid dune
#

ah so raycasting it is

leaden ice
#

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

timid dune
#

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

lean sail
#

That doesnt sound like a random vector then

timid dune
#

well without a normal how does one define what directions are possible?

leaden ice
#

Why do we need collision normals

lean sail
#

You have the object you hit and your own object

#

Just calculate the direction

timid dune
#

im not sure if I need them

lean sail
#

You definitely dont

leaden ice
#

surely the object that is moving or something that is moving it knows what direction it was being moved in

timid dune
#

let me draw up a quick diagram

#

only this one degree of freedom

lean sail
#

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

timid dune
#

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

lean sail
#

Are u not able to use a collider? Like does this specifically HAVE to be a trigger?

timid dune
#

not really but I was wondering if it was possible without 2 rigidbodies

#

since for the collisionenter you do need two rigidbodies

lean sail
#

No u dont

timid dune
#

really?

leaden ice
#

you need one dynamic body and two NON trigger colliders

timid dune
#

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

lean sail
#

yea the unity docs do word that one poorly imo

rain minnow
#

fast array? interesting . . .

trim rivet
#

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

leaden ice
#

so you're waiting an extra frame for no reason

trim rivet
#

oh, interesting... oh man yeah I guess that's pretty stupid

#

thank you!

raw tartan
#

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

swift falcon
#

What are some good examples for methods?

swift falcon
#

fair enough

dense estuary
#

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

lean sail
dense estuary
#

I should probably organize the script better

#

but, i fixed the launch pad, now i just need to keep momentum when launching off it

lean sail
rain minnow
#

Shouldn't adding force just add to the current velocity/force of the GameObject?

lean sail
#

OnCollisionStay you add force based on the current velocity but this might go wrong fast

dense estuary
lean sail
# dense estuary How so?

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

dense estuary
#

This is on the JumpPad script btw

hollow shard
#

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.

static matrix
#

ouch

lean sail
dense estuary
#

sorry, forgot to include that

compact spire
#

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?

leaden ice
compact spire
#

Fair enough... good to know

#

Thanks

night harness
#

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

raw tartan
#

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)

unreal temple
#

Is it possible to use Rigidbody2D interpolation with a kinematic rigidbody?

unreal temple
#

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);
}
night harness
#

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

unreal temple
#

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.

night harness
#

Right fair fair. I was looking for a way to make it super generic but im probably overthinking it, heard chef

#

tyty

raw tartan
#

does nobody know how to help me

lean sail
#

Other case u could probably make a new event without it

night harness
unreal temple
#

Does anyone know how to use interpolation with kinematic rigidbody2d?

#

is it possible? The docs don't say

raw tartan
#

thank u

latent latch
#

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.

unreal temple
#
[HideIf("HideMyField")]
public int MyField;

bool HideMyField(int value) {
  return (someEnum & (someFlag | someOtherFlag)) == 0;
}
latent latch
unreal temple
#

NA calls it

latent latch
#

Oh, I see

#

Ok, let me try that ;)

night harness
#

Is there a nice function for me to use to run code when the relevant object is selected in the inspector? (Using [ExecuteInEditMode])

unreal temple
#

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

night harness
#

Have to avoid OnDrawGizmosSelected because a lot of the time I have them disabled :/

latent latch
olive crypt
#

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

olive crypt
#

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

shell void
#

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?kekwait

coarse gull
#

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?

bright heron
#

for some reason my Cinemachine virtual camera wont move on the y axis, heres my code and camera

stable osprey
#

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

bright heron
#

oh wow yeah disabled the script and it won't rotate i can only move it around

stable osprey
bright heron
#

it turned out to be the look at playerroot

lyric drift
#

Any good dependancy injection frameworks out there?

stable osprey
pure cliff
pure cliff
stable osprey
#

well, for starters, let's start with stating that a DI plugin should not need an installer 😛

pure cliff
#

Hm?

leaden solstice
#

Zenject is bloated yeah but it works okay

#

Haven't tried VContainer yet

#

Others I know are quite dead

stable osprey
#

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); }
          }
    }
}
leaden solstice
stable osprey
#

I wish Unity would expose some event like UnityEngine.Object.OnAwake or smth :/

tiny orbit
#

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?

frozen dagger
#

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;
        }`
tawny elkBOT
#
Posting 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.

quartz folio
leaden solstice
tepid juniper
#

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.

lucid matrix
#

Hey, is there any free asset that will find every unreferenced scripts to remove those annoying warnings?

#

or is there anything inbuilt

lucid matrix
#

can you tell why this tells me there is behaviour missing? There is a script assigned to it and no console errors

cosmic rain
lucid matrix
#

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?

cosmic rain
#

Yep

lucid matrix
#

What should I do? Should I ignore ?

cosmic rain
#

Probably want to add the editor define as well

cosmic rain
lucid matrix
#

Ok, thanks!)

thin aurora
#

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

lucid matrix
#

Very clever, thanks! Let me try

cosmic rain
#

Might want to remove that screenshot as it seems to contain some sensitive data(keys).😅

lucid matrix
#

:d

#

Ah.. yeah

#

Thanks

#

and there are some like these:

#

with none. should I just remove them?

#

But there should be something attached

thin aurora
#

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

lucid matrix
#

I do not know the name of that script , have no idea.

quartz vessel
#

facing this error while integrating firebaseWebGL in unity

rigid island
muted root
#

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.

prime sinew
#

People that do editor scripting will hang out there

muted root
#

opsi hadn't seen that channel before, thanks 😅

dim rose
#

how do i bring this object to front

coarse gull
simple egret
# coarse gull 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

quartz vessel
# rigid island not easy to help without sharing at least the script

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.

nova crystal
#

anyone know how to apply a material to unitys Terrain ? (with code)

hexed pecan
nova crystal
#

nah its all good i found it

#

it was Terrain.MaterialTemplate

#

i was verry confused xD

carmine wind
#

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?

dusk apex
carmine wind
#

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

dusk apex
#

Relative to enum.

carmine wind
#

I did sadly it doesnt work

fair heron
carmine wind
#

I found something on google now but it's kind of a weird solution

dusk apex
carmine wind
dusk apex
#

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.

carmine wind
#

eh whatever I'll take a string and parse it to the enum 😴 thank you tho

dusk apex
#
public void Spawn() => Spawn(_spawnable);```
ornate moon
#

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?

swift falcon
#

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
mellow sigil
#

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

ashen yoke
#

UnityEvent is pain

mellow sigil
#

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

ashen yoke
#

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

ornate moon
#

Ugh. I feared as much.

ashen yoke
#

you can try those solutions from asset store like EasySave

#

never used them cant vouch

ornate moon
#

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

ashen yoke
#

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?

twilit shoal
#

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!

ashen yoke
#

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

ornate moon
#

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

ashen yoke
#

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

ornate moon
#

no, player prefs so far.

ashen yoke
#

any serialization library?

ornate moon
#

nope. Again I wanted a strarting point to tackle this. But it's so nebulios.

ashen yoke
#

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

ornate moon
#

Yes but it's a starting point I get.

ashen yoke
#

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

ornate moon
#

That's perfect, thank you.

ashen yoke
#

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

swift falcon
mellow sigil
#

It's your code, does it?

twilit shoal
timber jewel
#

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

knotty sun
timber jewel
#

🤔

timber jewel
dense vessel
#

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;
}
```)
dense vessel
#

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 😢

unique cloak
#

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.

rugged goblet
#

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

unique cloak
#

so this

foreach (GameObject food in in_range_available_food) 

will check all 20 object references in the array even if none are initialised?

rugged goblet
#

Would you expect foreach to automatically filter out null objects?

unique cloak
#

🫠 Yes?

#

I suppose not

rain minnow
#

No, the array just holds the value. You need to check if those values are null or not . . .

rugged goblet
#

If you are confused about the behaviour of foreach, I suggest reading documentation

unique cloak
#

Gotcha, thanks

gray mural
#

it checks everything, make sure it won't throw you any error

supple wagon
#

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

solemn rune
#

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?

modern creek
gray mural
#
public class DontDestroyOnLoad : MonoBehaviour
{
    private void Awake() => DontDestroyOnLoad(gameObject);
}
#

@supple wagon

earnest gazelle
#

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

modern creek
earnest gazelle
modern creek
#

I have a pretty low bug incidence for this sort of thing, so I don't check it

#

(150k line codebase)

earnest gazelle
#

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.

gray mural
#

yeah, scary one

#

a lot to fix

earnest gazelle
#

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{}
}
earnest gazelle
# gray mural you probably cannot
public class BaseClass: MonoBehaviour{
   //...
   private void OnEnable()
   {
      _instance.EventB += OnRaised;
   }
   private void OnDisblae()
   {
      _instance.EventB -= OnRaised;
   }
   public virtual void OnRaised(){/**/}
   
}
gray mural
#

you just += in OnEnable and -= OnDisable

#

not "just once"

earnest gazelle
#

instead of children. In some situations, it works

gray mural
#

so that it's done automatically when you subscribe

earnest gazelle
#

For example my noob colleague had defined instance as a protected one and then listen to that event in every children class

gray mural
earnest gazelle
#

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.

gray mural
#

@earnest gazelle

protected virtual void OnEnableBase()
{
    OnEnable(); // call Unity Message

    foo += Bla;
}
private override void OnEnableBase()
{
    base();

    bar += Nice
}
gaunt lake
#

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_;
};```
gaunt lake
#

It's in C++

gray mural
gaunt lake
#

What do you mean?

gray mural
rugged goblet
#

Why are you bringing C++ here?

gaunt lake
#

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#

rugged goblet
#

Looks like a constructor, but you're asking people who speak English about French

gray mural
#

not very reliable though

swift falcon
#

chatGPT is smart

gray mural
gaunt lake
gray mural
gray thunder
#

Dont get ChatGPT to write code for u

earnest gazelle
gray mural
gray thunder
#

chatgpt is fine for debugging

gray mural
earnest gazelle
#

It can return just templates

gray thunder
#

its for more superior in debugging than writing code

#

far*

gray mural
gray thunder
#

or error resolvement

gray mural
#

has anyone ever asked this.

#

don't ask why I need this

#

I don't actually

earnest gazelle
gray mural
shell scarab
#

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?

simple egret
#

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

ashen yoke
shell scarab
ashen yoke
#

meaning if you (int)(object)myInt there is a good chance compiler wont box

ashen yoke
#

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

shell scarab
#

what makes a reference type small and what is a small heap?

ashen yoke
#

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

shell scarab
#

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;
}
ashen yoke
#

a null check is dirt cheap, if its not null you are instantly dropping performance

#

again if you are microoptimizing dont do it

simple egret
#

The struct, without the bool, but enclosed in a Nullable

#

MyStruct?

dusk apex
#

Are you targeting a smaller memory footprint (quantitative) or stack vs heap (qualitative)?

shell scarab
#

not targeting anything.

dusk apex
#

GC is usually the concern, if it matters. Where heap allocation is slower than stack allocation.

shell scarab
dusk apex
#

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.

shell scarab
#

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.

ashen yoke
#

you can define record struct btw

#

not sure unity supports it

pure cliff
# gray thunder Dont get ChatGPT to write code for u

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

gray thunder
lean sail
#

And if you arent able to debug what it gives, you shouldnt even use it

shell scarab
#

which actually makes me remember a question, do unity projects have to be CLS compliant?

vast wigeon
#

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?

gray thunder
lean sail
#

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

dusk apex
#

How to post !code

tawny elkBOT
#
Posting 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.

dusk apex
#

Ah, guess it's a cross post.

vast wigeon
#

I mean what?

late lion
#

Records are a language feature. The runtime doesn't differentiate them from classes.

swift falcon
gray mural
swift falcon
zealous minnow
#

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.

rugged goblet
#

I'd say to start making something that seems fun, and you will learn along the way

gray mural
#

Hello, how to make value to be able to be changed just within script during runtime and not in the inspector?

somber nacelle
#

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

gray mural
#

I should be able to set it before game starts, not while game is running

somber nacelle
#

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

shell scarab
somber nacelle
#

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

gray mural
#

also it seems like making properties for every isn't very good idea

#

@somber nacelle thank you

late lion
shell scarab
#

ah, that makes sense.

pure cliff
#

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

mossy gust
#

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

wet pumice
mossy gust
#

fuuuck

wet pumice
#

make sure the class is serializable too

#

I believe the variables need to be

#

as well

mossy gust
#

i see

oblique spoke
#

Also, JsonUtility doesn't serialize bare collections without being wrapped in some struct or class

mossy gust
#

Ok

wet pumice
#

aye, arrays are a bit wonky too, there was a wrapper I found online for handling them

shell scarab
#

did I do this right?

#nullable enable
    private Command? command;
#nullable restore
somber nacelle
shell scarab
somber nacelle
#

then you don't need the nullable directive

shell scarab
#

I get a warning, CS8632

somber nacelle
#

that's regarding nullable reference types. what is Command

shell scarab
#

wait. I forgot to save the file :p oops.

timber jewel
#

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

cosmic rain
timber jewel
#

Alr thanks

#

Should be able to search now that you say that, didn’t really know what it was called

cosmic rain
timber jewel
#

Thanks that looks exactly like what I need

tiny pollen
#

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

pure cliff
#

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

native copper
#

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);
}
}
}

tribal ginkgo
#

Wouldnt you want to destroy collision.gameobject

rugged goblet
#

Let's start with !code

tawny elkBOT
#
Posting 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.

leaden ice
native copper
#

i used it to check if the bullet is colliding with walls and stuff

leaden ice
#

you should add logs to make sure that tag check is working

fierce forge
#

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;
    }

}
native copper
leaden ice
native copper
#

inside the first if statement

cosmic rain
fierce forge
#

thats why im confused, im not detecting tiles and still they are taking priority over ui

cosmic rain
fierce forge
cosmic rain
fierce forge
#

alr

#

wait

native copper
#

i changed it to comparetag

fierce forge
cosmic rain
somber nacelle
#

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

fierce forge
fierce forge
#

thanks for help ❤️ ❤️

timber jewel
fierce forge
urban kiln
#

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.

stable osprey
urban kiln
stable osprey
#

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 :/

urban kiln
#

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!!!

leaden ice
timber jewel
# cosmic rain I do t think so.

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

native copper
night harness
#

Might be worth logging what the tag collision has before that if statement to see if the right object is being hit

swift falcon
#

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;

}```
native copper
#

nvm i fixed it

#

thanks for your help anyway

stable osprey
#

np

noble mica
stable osprey
stable osprey
#

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

mellow night
#

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?

gray mural
#

Hello, I just wonder if it's even possible to pass value in UnityEngine.RangeAttribute ?

[SerializeField] [Range(min, max)] private int foo = 1;
hexed pecan
gray mural
#

why I cannot serialize const field?

#

is it always so?

hexed pecan
latent latch
#

think it's done at compilement time so you couldn't seralize it?

gray mural
#

but why can I use const fields that are below my fields with RangeAttribute?

latent latch
#

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

gray mural
#

but what's the difference between const and readonly then?

latent latch
#

oh yeah can you serialize readonly fields

#

ah, right you can set the object data variables, but only through the constructor

gray mural
#

const need to be defined at the time of assignment, while readonly field can be defined at runtime

latent latch
#

yeah true

gray mural
#

even though it cannot be selialized 🤔

latent latch
#

that was a question, but I would assume they would be serializable. /shrug

gray mural
swift falcon
#

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

https://media.discordapp.net/attachments/497872424281440267/1129636085090234418/20230715-0449-39.4258756.mp4

#

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.

pure cliff
# gray mural but what's the difference between const and readonly then?

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

untold plover
#

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.

rain minnow
thin aurora
# gray mural but what's the difference between const and readonly then?

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

gray mural
#

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

slender depot
#

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?

frosty jay
#

Shouldn't ScorePenalty be a negative number?

slender depot
#

uh it should be

gameControllerScore.ScorePenalty -= 10;

yes, but it should start at 45

#

still isnt changing yet either way

frosty jay
#

I'm assuming it is updating scoreText.text with a value equal to player.position.z is that correct?

slender depot
#

right.

scoreText.text = (player.position.z + ScorePenalty).ToString("0");
frosty jay
#

Have you tried hardcoding a value for ScorePenalty? Something like

scoreText.text = (player.position.z - 50).ToString("0");

slender depot
#

well, the 45 is working. just not the 10 being subtracted on death.

simple egret
#

Not sure how that would solve the issue yeah, it needs to be dynamic

frosty jay
#

Just general debugging to see where things are going wrong

simple egret
#

Make sure the code that adds some penalty runs, and that it's referring to the right script

slender depot
#

what do you mean?

simple egret
#

Also I'm assuming you aren't getting any errors, especially a NullReferenceException

slender depot
#

yeah I think I am getting that actually

#

not sure if it's resolved let me check

simple egret
#

That would have been nice to mention with your original question

slender depot
#

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

frosty jay
#

Oh bb no, try keep a clean console for your own sake, will make like easier

simple egret
#

These errors will stop all the code from running, you might not be even reaching the point where it adds the penalty

slender depot
#

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)

simple egret
#

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)

slender depot
#

which is this

gameControllerScore.ScorePenalty += 10;

simple egret
wooden cove
#

what would be a clear way to display these assets as temp

simple egret
#

Where do you put a value into this variable?

thin aurora
#

But not like that

slender depot
#
        gameControllerScore = gameController.GetComponent<Score>();
#

there

simple egret
#

Okay so, the object that's in gameController variable didn't have a Score script on it

thin aurora
#

Note you cannot use these in a coroutine

slender depot
#

oh no I did move it

#

but I was in play mode

#

omg

#

that fixed it

simple egret
#

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

ashen yoke
#

you are not calling this coroutine

slender depot
gray mural
thin aurora
#

Not this again

#

We had this chat

gray mural
simple egret
gray mural
mellow sigil
#

There's no point in using GetComponent here at all, just serialize the gameControllerScore field and drag the object there directly

thin aurora
#

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

wooden cove
#

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?

slender depot
ashen yoke
#

IEnumerable is not a collection its an interface

gray mural
ashen yoke
#

i can make a class with no fields storing nothing and it would be ienumerable

gray mural
#

just one

#

it's impossible I guess

ashen yoke
#

this smells hard of xy issue, what are you trying to achieve

simple egret
# slender depot they should just remove null tbh

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

gray mural
#

I though that I should have used yield return new WaitUntil(() => ...) and then return Vector2

ashen yoke
#

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

slender depot
gray mural
ashen yoke
#

you understand what happens when you start a coroutine?

thin aurora
gray mural
thin aurora
#

Or you yield one entry and the break from the method

ashen yoke
#

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

simple egret
#

Yeah coroutines are compiled into some elaborate state machines

#

Well, iterators

ashen yoke
#

thats it, there is no way for you to use returns there, only thing you can do is assigning by reference

#

ie

simple egret
#

Unity just hijacks the features

ashen yoke
#
IEnumerator foo()
{
    this.myVector2 = ...
}
gray mural
thin aurora
# gray mural what.?

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

thin aurora
#

It makes no sense because there is no yielding with a single result

simple egret
#

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

thin aurora
#

Or regular Tasks

gray mural
#
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;
}
simple egret
#

default

gray mural
simple egret
#

The coroutine did not have the time to run the assignment before execution reached the return

ashen yoke
#

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

gray mural
ashen yoke
#

this is normal c#

#

nothing abnormal

#

the only error you would get is StartCoroutine is not defined

rigid island
#

thats vector2 in normal c# , it doesn't have up property

simple egret
#

Yup from System.Numerics

gray mural
simple egret
#

The implementation is open sourced, you couldn't

gray mural
#

how do I start coroutine then?

wooden cove
#

he's making a joke cuz you said sue, not use

ashen yoke
#

start coroutine outside of unity?

gray mural
ashen yoke
#

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

rigid island
gray mural
#

I see

simple egret
#

Could make a method stub that takes in an IEnumerator, but it wouldn't do anything because it requires the whole engine below

gray mural
#

not the most interesting thing to do

rigid island
#

public async Task DoSomeWork()

gray mural
ashen yoke
rigid island
gray mural
gray mural
gray mural
ashen yoke
rigid island
ashen yoke
#

you get good by doing stuff like this

gray mural
#

thank you all for your help 🤯

wooden cove
#

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?

rigid island
ashen yoke
#

just a placeholder?

#

or hideflags?

#

or serialized in place?

wooden cove
#

placeholder meshes that should be removed and replaced for the final result

ashen yoke
#

replacement as in by artists, or some automation?

wooden cove
#

same applies for meshes that are under revision and marked for replacement

wooden cove
ashen yoke
#

so flagging the asset itself would suffice?

wooden cove
#

yes, since the dimensions of the asset will remain consistent but the mesh itself needs to be replaced.

ashen yoke
#

you can use asset labels

#

you can set them in code and read and base validation on it

rigid island
#

@slender depot ?

ashen yoke
#

editor only, but you are doing validation during build i assume

rigid island
#

why the x emoji @slender depot

wooden cove
#

but right now, its a MB with a bool flag xd

slender depot
ashen yoke
#

MB in a prefab?

wooden cove
#

aye

ashen yoke
#

you can flag prefab itself

#

with labels

rigid island
ashen yoke
#

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

wooden cove
#

oho, interesting

ashen yoke
#

and a simple hotkey to toggle label

wooden cove
#

how do you manipulate the hierarchy view and add to that tho?
Im not familiar with that

ashen yoke
#

the only downside, which is arguably not a downside, is that your source control can get spammy with labels

ashen yoke
#

let me check

#

oh not hierarchy, i meant project

#

but same goes for hierarchy

#

there is also a callback afaik

wooden cove
#

oh I see

#

hmm

ashen yoke
#

basically just using labels can get you very far

wooden cove
#

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

ashen yoke
#

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

wooden cove
#

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

wooden cove
#

@ashen yoke are those asset flags visible somewhere in the editor?

ashen yoke
#

bottom of the inspector

wooden cove
#

ah

ashen yoke
#

you can manually type them in

wooden cove
#

I just saw that too

#

these labels might see more use

#

they look really useful

ashen yoke
#

yep

wooden cove
#

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

ashen yoke
wooden cove
#

that works, right now im drawing a small rect but that seems more user-friendly

stark jacinth
#

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.

ashen yoke
#

put breakpoint at 54, and start the debugger while looking at the banana

leaden ice
ashen yoke
#

so a trycatch block costs about 30% more than direct call

#

maybe less, about 20%

#

which is great

stark jacinth
#

then I stopped debugging and got no errors

ashen yoke
#

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

stark jacinth
#

the game wont run when I start debugging in vs

ashen yoke
#

then in vs click attach to unity

stark jacinth
#

oh do I run the game first then debug

ashen yoke
#

most likely it starts, you just instantly hit the breakpoint

#

because your breakpoint is in update

stark jacinth
#

that wouldn't make sense though the banana's spawn point is not close to my player's spawn point

ashen yoke
#

it makes perfect sense since the breakpoint is in update

#

first update and its hit

stark jacinth
#

ok so I run the game first look at a banana then debug in vs

#

then see what I get

ashen yoke
#

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

stark jacinth
#

got no errors

#

places the spawn points right infront of my player

ashen yoke
#

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

stark jacinth
#

for my hitBanana it says "Object reference not set to an instance of an object"

#

then hitBanana.collider = null because of this

compact spire
#

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.

rugged goblet
#

For example, you could have your components subscribe to certain data when they register

compact spire
#

@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.

rugged goblet
#

Yeah unless you're finding yourself passing a ton of parameters just pass parameters

wheat relic
#

im only able to jump when moving, anyone can help a brother out?

compact spire
#

Fair enough, thanks

#

@wheat relic Maybe you are toggling CanMove to false somewhere?

rugged goblet
#

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

vernal compass
#

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?

wheat relic
compact spire
#

@wheat relic Ok then what about isgrounded?

vernal compass
wheat relic
compact spire
#

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?

wheat relic
#

how do i see that?

#

its not a public bool

compact spire
#

Debug.Log(characerController.isGrounded.ToString());

#

I think bool tostring works.

wheat relic
#

do i put that in the update?

compact spire
#

this is the jump right?

#

if(Input.GetButton("Jump") && canMove && characterController.isGrounded)
{
chargedPower += Time.deltaTime;

    }
wheat relic
#

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;

    }
compact spire
#

oh duh, I see

#

just break up your if staetment temporarily

wheat relic
#

what do you mean? 😂

#

im a total code noob

leaden ice
compact spire
#

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

leaden ice
#

there's no need to call ToString

#

it will be converted to a string automatically

compact spire
#

Yeah, wasn't sure on that

leaden ice
#

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}");```
wheat relic
#

this happened when i jumped

#

couldnt include this

pure cliff
#

why dont folks just use the debugger

leaden ice
#

it's also unecessary

wheat relic
#

what is necessary then

leaden ice
#

nothing

#

remove the ToString, as mentioned

wheat relic
#

i just wanna jump 😭

leaden ice
leaden ice
rigid island
#

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

leaden ice
wheat relic
#

so this happens when i move and am able to jump

#

when i stand still i cant jump and nothing shows up in console

pure cliff
rigid island
#

making a tutorial on it

#

apparently it doesn't like Vector3s

leaden ice
#

we know isGrounded is false then

#

we have learned what we wanted to learn

wheat relic
#

so isgrounded is false when i stand still

#

das wierd

rigid island
soft shard
leaden ice
wheat relic
rigid island
#

"unknown error " lmao
just say invalid serializable data or sum...wtf unity

wheat relic
rigid island
#

DateTime scruct actually serializes properly for it, can you believe this shit.. must be an oversight.

leaden ice
leaden ice
#

wdym

wheat relic
#

but i cant see the bool

#

for it

leaden ice
#

wdym

#

"see"

leaden ice
wheat relic
#

no bools

leaden ice
#

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

wheat relic
#

so its just competely unreliable and arbitrary in its ability to notice if im grounded or not

leaden ice
#

it's reliable if you understand how it works

#

but I already. recommended several times to you

#

don't use it

rigid island
# leaden ice it says "The Cloud Save editor accepts JSON Data Types. You must provide values ...

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..

leaden ice
#

use your own grounded check

wheat relic
#

idno how but ill try

rigid island
#

I guess DateTime good, Vector3 Bad 😦 oh well

rugged goblet
#

Vector3 isn't marked with the Serializable attribute and is not serializable by most serializers

rigid island
#

one of those weird Unity inconsistencies ig..

rigid island
#

back to making struct for v3 it is

#

the feature is too cool to ignore..

rugged goblet
#

I don't know why they haven't just marked it as serializable but I assume there's some reason

rigid island
soft shard
# wheat relic idno how but ill try

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

wheat relic
wheat relic
#

shieeeeeeeesh

leaden ice
#

they weren't saying to remove it and use THIS script

#

it'd be a completely different script to use a Rigidbody

wheat relic
soft shard
# wheat relic actually i need the cc in order for the code to work....

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

trim schooner
tulip temple
#

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

lavish frigate
#

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?

rigid island
#

like other value types.
Stack is faster cause its data is added and removed in a last-in-first-out manner, heap uses Pointers

compact spire
#

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?

tulip temple
tulip temple
#

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

soft shard
topaz ocean
#

How do I make it so EditorGuiLayout Fields trigger "OnValidate"?

rigid island
tulip temple
#

okay i see

ashen sage
#

quick question: whats the difference between using interfaces and abstract classes?

trim ferry
#

i got a script from a youtuber, i set it up all correctly but it shows me this error:

#

the line

#

and the properties

topaz ocean
trim ferry
#

please help

ashen sage
ashen sage
topaz ocean
ashen sage
#

ok...

trim ferry
#

should I?

ashen sage
#

no need, yet

#

so

#

as error says you didnt reference an object to a variable

trim ferry
#

yes but i referenced it

#

i presume

ashen sage
#

did you reference it through script or inspector?

leaden ice
# trim ferry

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

trim ferry
#

wdym

leaden ice
#

transform.parent returns null if your object doesn't have a parent

#

so you're trying to do null.up

#

which is an error

ashen sage
#

in hierarchy you have to drag the scriptholder object on another object

trim ferry
#

but it has one

#

look at hierarchy

leaden ice
#

PulseTurret has no parent

#

(or if it does we can't see it from this screenshot because you cut it off)

ashen sage
#

scroll a little up and screenshot

trim ferry
#

wait, i need to make an empty gameobject with the script and make PulseTurret a child?

leaden ice
#

why are you writing transform.parent.up if it is not expected to have a parent

ashen sage
trim ferry
leaden ice
ashen sage
#

yep it has no parent

#

try dragging the pulseturret on MainBody, i assume the spider has to hold the turret?

leaden ice
#

uhhh

#

or just go back to your tutorial and make sure you did things properly

#

I wouldn't start randomly dragging stuff around

trim ferry
ashen sage
#

send us video link

leaden ice
#

you still have the script on an object that doesn't have a parent

trim ferry
#

oh

ashen sage
#

can u send a little more of the code

trim ferry
#

yeah

#

srry

ashen sage
#

nvm

leaden ice
trim ferry
#

wtf is happening

leaden ice
#

See how in the video that script is on an object that is a child of the root object?

trim ferry
#

its rotating up and down in the z axis

ashen sage