#archived-code-general

1 messages · Page 52 of 1

wooden cove
#

quite randomly I might add

#

or at least it feels as such

quartz folio
#

is it based on where you look

fluid lily
# wooden cove quite randomly I might add

That sounds like some scripting thing, unless you are saying just visually disappearing. Try changing the shader on the object, other wise there are a few tools you can use to find all references to the object being used.

wooden cove
quartz folio
#

Have you checked the bounding box of your object?

#

If you're positioning it via shaders for example, then the bounding box isn't where the mesh is

wooden cove
#

you think the object might be considered outside the frustum?

quartz folio
#

so it'll disappear when you stop looking where the mesh is actually positioned

wooden cove
#

we are not using shaders to manipulate the geometry in any way

quartz folio
#

this can also happen with animated objects, sometimes you have to set them to not be culled or recalculate their bounds

wooden cove
#

the objects are also not animated

#

they are static meshes that are placed on an AR plane

#

each only has a few materials, with a default lit shader

quartz folio
#

No idea then, I can only imagine it's an AR-specific issue

fluid lily
wooden cove
fluid lily
#

Another aproach would be make a empty scene with that object and a camera. At this point you will probably just have to track down one thing at a time.

wooden cove
fluid lily
wraith knot
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class dapipe_script : MonoBehaviour
{
    public float movespeed=5;
    public float deadzone = -30;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        transform.position += (Vector3.left * movespeed) * Time.deltaTime; 

        if (transfrom.position.x < deadzone)
        {
            Destroy(gameObject);
        }
    }
}
#

i need help with this

#

the if statement is not working

wooden cove
fleet furnace
wraith knot
#

how can i

#

im new here

fleet furnace
unreal temple
#

If an artist has set a serialized color field to a color, and we want to convert that value to HDR, how can I do this?

#

I'm assuming that adding the ColorUsageAttribute will not reserialize the value.

#

(I'm assuming the data is interpreted differently for HDR, I don't know much abou this, just that the colors are rendering wrong)

quartz folio
#

It's fine, LDR and HDR values overlap the same

#

At least, I thought they did

unreal temple
#

Our issue is that when I set the colors in a VFX graph they're wrong.

#

So the lines of color overlayed (red+blue, yellow+red) are fromt he inspector

#

They're setting the colors in the bullets, which are much paler than in the inspector.

#

But when we set those colors in the VFX graph inspector they are true to the serialized value.

quartz folio
#

It could be a blending issue, post processing, or... a linear vs gamma problem

unreal temple
#

woudl be my guess

#

But they're just Color values right?

#

Or maybe the fields in the VFX graph are special in some way

quartz folio
unreal temple
#

But that does seem like the problem.

#

Okay, I'll try converting the value to linear space?

#

or... gamma space

#

lol I'm in over my head

#

I'll try both ways and see which works

quartz folio
#

That's what I try

#

Every time there's a colour issue I'm there with the conversions just to check

unreal temple
#

haha, yeah when we changed the project to linear space everything became pastel

#

So I'm guessing it's gamma being read as linear

#

Thanks @quartz folio ❤️

violet cipher
#

I keep having an error with a ?: operator

#

`public class Movement : MonoBehaviour
{
private Rigidbody2D rb;
public float moveSpeed;
public float rbacceleration = 7;
public float rbdecceleration = 7;
private bool facingRight = true;
public float velPower;
public int moveInput = 0;

// Start is called before the first frame update
void Start()
{
    rb = GetComponent<Rigidbody2D>();
}

// Update is called once per frame
void Update()
{
    if (Input.GetKey(KeyCode.D))
    {
        moveInput = 1;
    }
    else if (Input.GetKey(KeyCode.A))
    {
        moveInput = -1;
    }

    if (Input.GetKeyUp(KeyCode.D))
    {
        moveInput = 0;
    }
    else if (Input.GetKeyUp(KeyCode.A))
    {
        moveInput = 0;
    }

    //calculate the direction we want to move in and our desired velocity
    float targetSpeed = moveInput * moveSpeed;
    //calculate difference between current velocity and desired velocity
    float speedDif = targetSpeed - rb.velocity.x;
    //Calculate if our moveInput is 0 it will de accelerate, anything higher than 00.1 will make us accelerate
    float accelRate = (Mathf.Abs(targetSpeed) > 0,01f) ? rbacceleration : rbdecceleration;`
#

I get the error: Cannot implicitly convert type '(bool, float)' to 'bool'

#

but im not converting a bool to a float as far as i checked

#

rbacceleration & rbdecceleration both have a float value of 7

#

so accelrate should be 7 then

#

it's very confusing to me

knotty sun
violet cipher
#

wow...

#

i feel so dumb rn

#

Thank you so much btw

orchid bane
#

Is there a collection like Dictionary but which allows to get values the other way around too?

#
collection[a] //returns b
collection[b] //returns a```
#

Something like this

unreal temple
#

Although... there may be another solution

#

What is the type of the dictionary?

orchid bane
#

I don't really need multiple values to the same key, only 1

#

A reference type

unreal temple
#

?

#

I mean what types are key + value

#

Both the same type?

orchid bane
#

Yeah

cosmic rain
unreal temple
#

Then just enter everything twice.

cosmic rain
#

That could work👆

unreal temple
#

Potenitally you could do this too

#
HashSet<(MyType, MyType)> _set;
#

But that's only if you want to check if the connection exists

#

If you want to actually retrieve the other value just enter everything twice.

#

So like:

void LinkTheseThings(Foo a, Foo b) {
  collection[a] = b;
  collection[b] = a;
}

void RemoveThisThing(Foo a) {
  if (collection.TryGetValue(a, out var b)) {
    collection.Remove(b);
  }
  collection.Remove(a);
}
orchid bane
#

HashSet will do, thank you

summer nebula
#

what.. is a hashset

unreal temple
#

It's easy with integers etc

#

But the hashset needs to have the keys in a predictable order

#

For example:

bool LinkExists(int a, int b) {
  (int, int) key = Sort(a, b);
  return _hashSet.Contains(key);
}
#

It's a bit harder with references

orchid bane
#

Then will have to think about something else

unreal temple
#

I might have an idea if you have the use case

#

and you want it

orchid bane
#

Well

#

I have nodes

#

Like these ones

unreal temple
#

Ah cool, so these are the eges?

orchid bane
#

And I'm trying to create the trails properly

cosmic rain
#

Oh I almost got that job on upwork😭

#

Well, it wasn't that great to be honest.

unreal temple
#

Hey don't shit on telov

orchid bane
#

So I thought of starting with a random node and then going all over its connections creating trails

#

Meanwhile storing the created pairs so that I do not create duplicates

#

That's what I'm trying to do

cosmic rain
#

Just create a Node class with a list of Nodes

unreal temple
#

Yeah, I'd probably do that too.

#

Easiest for recursion

#
class Node {
  List<Node> _edges;
}
orchid bane
#

I have this for now

public class Node : MonoBehaviour
{
    [SerializeField] public List<Node> connections;

    private void OnValidate()
    {
        foreach (var node in connections)
        {
            if (!node.connections.Contains(this))
            {
                node.connections.Add(this);
            }
        }
    }
}```
unreal temple
#

well then you don't need a dictionary

#

You can just do:

if (node.Connections.Contains(otherNode)) {
orchid bane
#

But they both have each other

cosmic rain
#

So what?

unreal temple
#

A graph is like a doubly linked list

#

If A -> B but B is not connected to A then it means you can move from a to B, but not from B to A

#

In this example everything is doubly linked

#

Alternatively you can give each node an ID and then use the HashSet example from above

#

I would consider that option

#

Just make sure that all the nodes are created with a unique ID

#

If you have an array of nodes it can be their index

#

But there's nothing wrong with this:

static void Link(Node a, Node b) {
  if (!a._connections.Contains(b)) a._connections.Add(b);
  if (!b._connections.Contains(a)) b._connections.Add(a);
}
orchid bane
#

I'll just create a recursion I guess

solemn prism
#

Hello guys Iam making a vr project for school and iam trying to make objects have an outline when you touch them but I can't find anything on it online is there anyone here that could help me?

solemn prism
fiery oracle
cosmic rain
fiery oracle
#

What do they mean by "(occlusion areas) These areas are typically where the camera can go through."

craggy veldt
# orchid bane Like these ones

each node should have two ports, e.g: output and input, this way it would be very easy to sort things out
and those ports can accept multiple inputs/outputs from multiple nodes. Similar to GraphView api

fiery oracle
#

More specifically, how do you decide where to set the occlusion area?

cosmic rain
fiery oracle
#

I mean manually setting the box area. How do you decide the bounds of each occlussion area box?

cosmic rain
#

Areas closest to the player

#

unity docs do a better job at explaining

rustic ember
#

I want GridPos2D to be like the Vector2, just with integers. How can I make x and y show in the inspector?

somber nacelle
#

you know Vector2Int exists already, right?

rustic ember
#

You are a literal life saver. For years I had no idea 🙃

somber nacelle
#

Well now you do!
Also in regards to the issue you presented, as long as you have a serialized field of type GridPos2D it will show in the inspector

snow moat
#

Hello,
I used the localization package
But when I have a "\n" in my localized string, we see these on the screens.
How can I add newline in my localization ?
Thx in advance

lost wave
#

when switching from level two to level three, an animator controller for the transition fade, deletes from the inspector. it works fine from level 1 to 2.

crude mortar
#

it turns it into a toggle button where the float will be 1 or 0 depending on the toggle state

placid summit
#

Anyone use git source control and how do you manage large binary files (LFS support)?

#

is it fine 'out of the box'?

celest moss
#

Hey is there a best practice for handling the communication between multiple Managers?

cosmic rain
#

One manager to rule them all🤔

molten sandal
#

Question:

#

Given this piece of code:

RaycastHit hit;

trackDetected = Physics.SphereCast(transform.position, sphereRadius, transform.TransformDirection(-Vector3.up), out hit, rayDistance, layerMask);

Vector3 normal = hit.normal;
#

Is hit.normal in world space or in local space?

crude mortar
#

it is always the world space normal

molten sandal
#

kk, thanks

#

and hit.point? also world space?

crude mortar
#

yes

thick socket
#

how does the 2nd shorter version of this error but not the first 2 liner?

leaden ice
#

colorOverLifetime is a property and it's a struct

#

so you'd only be modifying a copy

#

strangely enough, the way Unity implemented the particle system modules this wouldn't actually be an issue - but C# doesn't allow it to prevent potential bugs

thick socket
#

gotcha

#

the piece I don't follow is how setting it to a variable then setting color works

#

yet making it all in 1 line doesnt

leaden ice
#

because it doesn't want you to lose the changes

thick socket
#

gotcha thanks

leaden ice
#

but again, since Unity implemented these structs in a weird way, it wouldn't actually be an issue like it normally would

thin aurora
# thick socket

Considering it's a struct, hence value type, the first two lines won't work either

leaden ice
#

for example for a Vector3 this would be an issue

leaden ice
#

Unity implemented the structs this way

thin aurora
#

Unity changed the way structs work?

leaden ice
#

color is a property that actually sets the native data properly

thin aurora
#

Lol this engine

leaden ice
#

it's not a change in how structs work

#

it's a property, not a field

thin aurora
#

They made it so complicated

leaden ice
#

yes

#

they should have just done it normally, but Unity is Unity 😆

#

I think they thought they were simplifying it

late lion
#

What would have been the normal way?

leaden ice
#

item.colorOverLifetime = col; (after making your changes)

thick socket
#

that would have made more sense in my mind lol

#
NullReferenceException: Do not create your own module instances, get them from a ParticleSystem instance
#
void SetParticleColors(bool isDefault)
    {
        Gradient grad = new();
        RarityColors rColors = new();
        //item
        if (isDefault)
        {
            grad.SetKeys(
            new GradientColorKey[] { new GradientColorKey(Color.white, 0.0f), new GradientColorKey(new Color(0.00392f, 0.20784f, 0.30980f), 0.6f) },
            new GradientAlphaKey[] { new GradientAlphaKey(0.0f, 0.0f), new GradientAlphaKey(0.6f, 0.13f),
                new GradientAlphaKey(0.6f, 0.83f), new GradientAlphaKey(0.0f, 1.0f) });
        }

        foreach (var item in allParticles)
        {
            var col = item.colorOverLifetime;
            col.color = grad;
        }
    }```
#

its getting mad at me for the col.color = grad;

#

Im not sure why...I followed the unity documentation for it

thick socket
#

ah dang, looks like I missed serializing one in editor

late lion
#

Oops, that would be because Unity's fake null object in the editor. Instead of assigning null, Unity will assign an object that is supposed to throw a "MissingReferenceException" if any of its properties or methods are accessed, but I guess they forgot to do that for ParticleSystem modules.

pure flint
#

Hi im new here so I dont know if this is the right channel to ask how to code specific thing but here goes.
So I made a List/Array. And I want to Instantiate those game objects and I did it. It worked BUT I want it to instantiate limitly for example
Gameobject A, B, C, D
so I want to instantiate gameobject A and B from the array/list without game obeject C and D being instantiated.

marble cove
#

Hello idk if this is to place to ask, but idk what to do, i have a script called item, whenever a gameobject with this script becames a child its stops updating, the script remains enabled but it stops updating(the gameobject is active too), what is this? how can i fix it?

leaden ice
leaden ice
pure flint
leaden ice
marble cove
leaden ice
#
for (int i = 0; i < 3; i++) {
  ...
}```
leaden ice
#

Share details if you're still confused

marble cove
#

okay

leaden ice
pure flint
#

It works thank you. I dont know why I didn't think of it

marble cove
# leaden ice prove it

i have this script as you see there is a print that should be alway print "!" but when i make the object a child it stops

#

and you can see it here that its enabled

#

and nothing happens it just stops updating

leaden ice
#

show the hierarchy when it stops

#

etc

#

also you really should not be doing FindObjectOfType in Update - let alone multiple times. But that's a separate discussion

marble cove
#

the player is the root

leaden ice
#

and show the inspector for Crucifix, as well as the console window

marble cove
#

it stopeed after 4

#

because thats when i picked it up

leaden ice
#

The script in question is Item?

marble cove
#

yes

leaden ice
#

Based on what you showed - it shouldn't stop updating. What happens if you restart Unity?

marble cove
#

let me try it, but in my understanding that shouldnt change anything cuz unity compiles the game every time i hit play and that should fix an error like this

leaden ice
#

Nothing should stop Update as long as the GameObject is active and the component is enabled

marble cove
#

it stops after restart too 🥲

marble cove
#

i work in unity for a good time now and i never see something like this

leaden ice
#

Nor have I 🤔

marble cove
#

and the funnier that this is an lts version of unity so it should popped up before

#

and the even funnier bit that when i unchild the item object it continues updating

leaden ice
#

maybe it's deactivating and reactivating the item every frame or something

#

that could interrupt Update

marble cove
#

it just one call when the player pressed pickup

leaden ice
#

how do you handle activating and deactivating the hands_n objects?

marble cove
#

this code runs when something happens that sould change the hand sprite, then it stores the current index of that sprite in the "righthand" variable

leaden ice
#

exactly what I was thinking

#

you're deactivating them all in that loop

#
for (int i = 0; i < Hands.GetChild(0).childCount; i++) {
  Hands.GetChild(0).GetChild(i).gameObject.SetActive(i == r);
  Hands.GetChild(1).GetChild(i).gameObject.SetActive(i == l);
}```
Try replacing the loop and the two lines after it with this ^
#

Right now you're deactivating then reactivating each frame probably. So it appears always active in the inspector/hierarchy, but you're not letting Update run.

marble cove
#

i fooouuund the problem thanks to your idea of something disrupting the update, it was an else if, that should be just an if

#

thank you very much!

coral kettle
#

does anyone know if a quick way exists to make the values of 1 script match another of do I need to 1 by 1 copy them over?

#

2 difference instances of the same script

coral kettle
#

I mean in code

#

at runtime

pearl swallow
#
if (plantIndex == 0)
        {
            transform.position = new Vector3 (tunnelArray[0].transform.position.x, tunnelArray[0].transform.position.y-10, tunnelArray[0].transform.position.z);
        }

So I'm trying to have a GameObject move down in y value by a certain value. I've tried other versions of it, to no success. I've had done it before, but now I'm not sure why it is no longer working.

#

Wait-

knotty sun
pearl swallow
#

Would I just subtract it by not including the tunnel array part?

ocean quail
pearl swallow
#

The array has a certain number of empty GameObjects that do not change actively, it's a list of transform values.

ocean quail
#

Is each element supposed to represent an offset?

pearl swallow
#

It is supposed to represent a new position that the GameObject moves to when the PlantIndex, which is a random), adjusts accordingly.

#

It's just in a certain instance of the code, it is supposed to move down by 10 until I can get an animation done for the object.

#

It's meant to be a placeholder code to represent what the animation is supposed to do.

#

It moves to the positions just fine.

#

I just can't subtract the Y value.

#

From the y value*

ocean quail
#

There's nothing wrong with that code, assuming index is 0 it should be set to Tunnel0-10. I would make sure 100% that that code is running, and furthermore that something else isn't resetting the position back to something else.

pearl swallow
#
transform.position = tunnelArray[0].transform.position;

This is in the start method but that shouldn't do anything but set up the initial.

#

Another section has it move back into the regular position (no subtraction to Y), but that wouldn't be called unless the other if statement in the update method had the parameters set.

leaden ice
pearl swallow
#
   public void PlantTunnel()
    {
        plantIndex = Random.Range(0, 3);
        plantStatus = 1;

        if (plantIndex == 0)
        {
            transform.position = new Vector3 (tunnelArray[0].transform.position.x, tunnelArray[0].transform.position.y-10, tunnelArray[0].transform.position.z);
        }

        else if(plantIndex == 1)
        {
            transform.position = new Vector3(tunnelArray[1].transform.position.x, tunnelArray[1].transform.position.y - 10, tunnelArray[1].transform.position.z);
        }
        else if (plantIndex == 2)
        {
            transform.position = new Vector3(tunnelArray[2].transform.position.x, tunnelArray[2].transform.position.y - 10, tunnelArray[2].transform.position.z);
        }

        else
        {
            transform.position = new Vector3(tunnelArray[3].transform.position.x, tunnelArray[3].transform.position.y - 10, tunnelArray[3].transform.position.z); ;
        }

    }
leaden ice
#
transform.position = new Vector3 (tunnelArray[plantIndex].transform.position.x, tunnelArray[plantIndex].transform.position.y-10, tunnelArray[plantIndex].transform.position.z);```
#

this replaces ALL of those if/else blocks

crude mortar
#

also Random.Range is exclusive, so it will never choose the final array element

pearl swallow
#

I was following stuff from google and etc.

#

I try to use that before going to here.

#

Which I should stop doing since this is a valuable resource.

crude mortar
#

arrays exist to avoid this exact kind of repeated code, for future reference

pearl swallow
#

Huh

#

Thanks

leaden ice
#

If you ever find yourself explicitly writing a number in like someArray[1] you should stop and think - you're probably doing something wrong

#

it should almost always be a variable

#

likewise if you're repeating the same code for different indices

pearl swallow
#

I don't really mess around with arrays too often, so I'm not knowledgable in them.

leaden ice
#

Also a somewhat less verbose (and more performant) way to do this:

transform.position = tunnelArray[plantIndex].position + new Vector3(0, -10, 0);```
pearl swallow
#

Thanks

#
public void PlantUntunnel()
    {
        transform.position = tunnelArray[plantIndex].transform.position;
    }

So for this method, it should just move it to the original position of whatever tunnel has been selected?

#

I adjusted it to match what you gave me.

crude mortar
#

assuming the position of whatever is in the tunnelArray isn't changing, then that sounds correct

pearl swallow
#

Well, it didn't...

#

Lemme copy the rest.

#
    void Start()
    {
        transform.position = tunnelArray[0].transform.position;
        plantStatus = 0;

        navMeshAgent = GetComponent<NavMeshAgent>();
    }

    // Update is called once per frame
    void Update()
    {

        //Creates a tunneling system for the Plant based on time.
        plantTime += Time.deltaTime * plantInSeconds;

        if (plantStatus == 0 && plantTime >= 10)
        {
            PlantTunnel();
            plantTime = 0;
        }

        if (plantStatus == 1 && plantTime >= 5)
        {
            PlantUntunnel();
            plantTime = 0;
        }

        if (plantStatus == 2 && plantTime >= 2)
        {
            plantStatus = 0;
            plantTime = 0;
        }

        //Sets distance from player for shooting or biting.
        playerDistance = Vector3.Distance(player.position, transform.position);

        if(playerDistance <= plantRange && plantStatus == 0)
        {
            transform.LookAt(new Vector3(player.position.x, transform.position.y, player.position.z));

            if (fireCountdown <= 0f)
            {
                GameObject poison = Instantiate(poisonProj, poisonSpot.position, transform.rotation);
                poison.GetComponent<Rigidbody>().AddRelativeForce(Vector3.forward*500);

                fireCountdown = 10f / fireRate;
            }
            fireCountdown -= Time.deltaTime;
        }
        
    }

This is the rest minus anything above start.

crude mortar
#

where are you changing plantStatus now?

leaden ice
#

Use a paste site and share the whole script 🙏

crude mortar
#

when preator said that his code replaced all the if statements, I think you accidentally removed that as well

pearl swallow
chrome thistle
#

When I transition to another camera, there is a little delay where do I remove that? Timeline with cinemachine!

pearl swallow
#

Second index was removed because it was causing conflicts, basically my attempt to do a non-repeating random (which I quickly realized does nothing.)

#

It should work, I don't see anything that is overriding it... unless I need parenthesis-

#

Hold on.

#

No, okay, didn't do anything.

pearl swallow
#

I’ll keep looking around in a bit, I gotta eat.

slim adder
#

How do I get all objects which lay in the game on top of the object?

#

I am trying to use Physics.Boxcast but it doesn't work

#

Is boxcast the right thing to use in Unity3d?

#

Or how should I do it?

rustic rain
#

This code is not working

#

i am using the new input system

#

and clicking on the gun doesnt have any effect

leaden ice
#

Any errors in console?

rustic rain
#

is there a way to regenerate the eventsystem?

leaden ice
slim adder
#

Okay great thank you!

thick socket
#
 public event Action<Items> addItem;
    public void AddItem(ItemReqs itemReq)
    {
        //addItem?.Invoke();
        Items item = new(itemReq);
        addItem?.Invoke(item);
        List<Items> tmpList = FindList(item);
        tmpList.Add(item);
    }
    public void AddItem(Items item)
    {
        addItem?.Invoke(item);
        List<Items> tmpList = FindList(item);
        tmpList.Add(item);
    }
#

first try using events...thought I had this setup right from the example Im following so not sure what is wrong

leaden ice
#

you can't just use the class name

rustic rain
leaden ice
thick socket
leaden ice
#

the way you have it now seems confusing because it seems like it is actually adding the item rather than a reaction to adding the item

leaden ice
thick socket
#

(following some tutorial that had things with collectable class that other subscribed to)

leaden ice
#

the event is a non-static member, so you need an object reference

#

If you use a static event you don't need an object reference.

#

of course that has other pitfalls 😉

thick socket
rustic rain
#

is it bad that i have different canvases for different things?

leaden ice
#

no

rustic rain
#

so what could be causing my issue then? im slightly confused

leaden ice
#

For example a fullscreen image on one of the canvases that's in front of this one

rustic rain
#

theyre all inactive tthough i believe, i'll have a double check though

leaden ice
#

just for testing - disable you other canvases

#

and see if it works

pearl swallow
rustic rain
leaden ice
rustic rain
leaden ice
#

so it's fine

rustic rain
#

oh wait

vagrant agate
#

Is there a way to get the height of an canvas image in world units without me doing my own screen calculation.

rustic rain
#

i think the debug for comments was disabled 💀 @leaden ice

#

it was working this whole time

#

i didnt see that LMAO sorry

#

thanks for your help though

pearl swallow
neon plank
#

How can I request to not Burst compile some methods in a job?

[BurstCompile]
private struct MyJob : IJob
{
     // Not Burst this
     public void Execute()
     {
          ManagedCode();
          UnamangedCode();
     }

     // Not Burst this
     void ManagedCode() {}

     [BurstCompile]
     void UnamangedCode() {}
}
lucid valley
#

On IJob and IJobParallel you have to put [BurstCompile] on Execute as well for it to be burst compiled

lucid valley
#

nope

#

nope

#

do not fall for that trap

#

it doesnt work like that

leaden ice
#

Lol

lucid valley
#

[BurstDiscard] literally means the code wont be compiled when burst is on

leaden ice
#

Oof

#

Not sure you can get method level granularity with it

#

It's at the job level right?

wintry crescent
#

Hi, should I grab input always in Update, or is FixedUpdate fine? Assuming I'm using Input.GetAxis (no GetKeyDown etc.)

somber nacelle
lucid valley
leaden ice
#

The idea is that Update is the exact cadence that input data updates so you will be reading it exactly when it may change. No more no less.

neon plank
leaden ice
#

Are you trying to access managed objects or something?

neon plank
#

Half the job uses managed code, half the job doesn't, my goal was:

void Execute(int index, TransformAccess transform)
{
    Managed1(...);
    Unmanaged1(...);
    Managed2(...);
    Unamanaged2(...);
    Managed3(...);
}

And apply BurstCompile to the unmanaged ones.

lament mural
#

I'm using a character controller for my player. I noticed that when platforms collide with the player, they don't always push it. If the player is standing completely still, the platforms will pass right through it. Does anyone know how to fix this?

leaden ice
lucid valley
#

you technically can through statics (not that doing that is recommended as it avoids the safety system)

neon plank
#

It works, but the Burst fail

lucid valley
#

you just can't pass them into the struct

neon plank
#

In my code, since this is a global manager, I just used static to get the managed data

lucid valley
#

whats the error?

leaden ice
#

I have no idea then

#

guess I was mistaken

leaden ice
neon plank
neon plank
lucid valley
#

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

lucid valley
#

just before I go and open Unity and try doing it myself

neon plank
#

The job start at lines 286

modern creek
#

I can't brain this morning. I want this gel ball to bounce around at a constant speed, but ... it's not. Any ideas?

        private IEnumerator GelFloatCoroutine()
        {
            Vector2 endPos = GetNextGelLocation();
            float _duration = Mathf.Abs(((Vector2)transform.position - endPos).magnitude / 800f);
            _currentTween = transform.DOLocalMove(endPos, _duration).SetEase(Ease.Linear);
            yield return _currentTween.Play().WaitForCompletion();
            transform.localPosition = endPos;
            DoNextAnimation();
        }

GetNextGelLocation() gets a Vector2 along the edge of the screen

#

oh!

#

.position and not .localPosition

#

🤦‍♂️

lucid valley
#

I guess Execute is always burst compiled with that attribute

#

I guess the way to get around it is to have the logic in a separate class

wintry crescent
#

I am heartbroken to discover that those are worldPosition. Is there an easy way to make a rigidbody be constrained in localPosition?

neon plank
modern creek
wintry crescent
lucid valley
#

thats the work around

neon plank
#

Ok, thanks

#

BTW, it's me or if I apply BurstCompile to a method, it will "propagate" that attribute to any method that it calls (i.e: it will also Burst compile them)?

neon plank
#

Interesting

lucid valley
#

so if you have any downstream managed stuff then you can't use burst

neon plank
#

Ok

abstract cypress
#

The line 108 throws a StackOverflowException. _replayBuffer is a Queue and this method is called up to 60 times a second. How do I avoid the StackOverflowException and why does it happen?

neon plank
#

Is there any reverse P/invoke or stuff that I can use to call managed code from Burst?

#

Just wondering

leaden ice
thick socket
#
public void SetPlayerStats()
    {
        int hp = 500;
        int atk = 100;
        foreach (var item in EquippedList.Values)
        {
            if(item !=null)
            {
                hp += item.hp;
                atk += item.atk;
            }
        }
        GameManager.instance.player.SetStats(hp, atk);
    }```
Having this called in constructor of class throws errors...however having it set in another class like this doesnt...any ideas why?
#
 playerInventory = new();
        ExampleInvAdd();
        playerInventory.SetPlayerStats();
silk horizon
#

Hello

lucid valley
#

which part in this is null GameManager.instance.player?

thick socket
#

nope

leaden ice
lucid valley
#

something hasnt been set up in time

leaden ice
#

Also share the error(s)

thick socket
#

neither is GameManager.instance.player.stats

thick socket
#

playerstats are setup in awake

#
NullReferenceException: Object reference not set to an instance of an object
PlayerInventory.SetPlayerStats () (at Assets/Scripts/Inventory/PlayerInventory.cs:212)
PlayerInventory..ctor () (at Assets/Scripts/Inventory/PlayerInventory.cs:31)
UnityEngine.Resources:Load(String)
BootStrapper:Execute() (at Assets/Scripts/DontDestroy/BootStrapper.cs:6)
#
NullReferenceException: Object reference not set to an instance of an object
PlayerInventory.SetPlayerStats () (at Assets/Scripts/Inventory/PlayerInventory.cs:212)
PlayerInventory..ctor () (at Assets/Scripts/Inventory/PlayerInventory.cs:31)
UnityEngine.Object:Instantiate(Object)
BootStrapper:Execute() (at Assets/Scripts/DontDestroy/BootStrapper.cs:6)


lucid valley
#

well is the GameManager instance also set in awake?

lucid valley
#

...

#

can you see the issue

thick socket
#

player is set publicly

leaden ice
thick socket
#

aka drag in

thick socket
leaden ice
#

Awake is before Start

thick socket
#
public class GameManager : MonoBehaviour
{
    public static GameManager instance;
    public void Awake()
    {
        instance = this;
    }
    public void Start()
    {
        //could try 60 also for ex)
        Application.targetFrameRate = Screen.currentResolution.refreshRate;
        Scene a = new Scene();
        LoadSceneMode b = new LoadSceneMode();

        SceneManager.sceneLoaded += LoadState;
        SceneManager.sceneLoaded += FindPlayer;
        SceneManager.sceneLoaded += FindEnemies;
        LoadState(a, b);
        FindPlayer(a, b);
        FindEnemies(a, b);
        playerInventory = new();
        ExampleInvAdd();
        playerInventory.SetPlayerStats();
    }```
leaden ice
#

Where does BootStrapper:Execute() run

thick socket
#
public class Player : Fighter
{
    float movement;
    bool jump;
    bool down;
    protected TextMeshProUGUI hpText;
    [SerializeField] Joystick joystick;
    [SerializeField] Button jumpButton;

    [SerializeField] int atk = 3;
    [SerializeField] float atkspd = 1f;
    [SerializeField] int multishot = 1;
    [SerializeField] Transform head;

    bool isMobile = false;
    protected override void Awake()
    {
        base.Awake();
        myJumps.maxJumps = 2;
        stats.attackDmg = atk;
        stats.attackSpeed = atkspd;
        stats.multiShot = multishot;
    }```
leaden ice
thick socket
# leaden ice Where does `BootStrapper:Execute() ` run
using UnityEngine;

public static class BootStrapper
{
    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
    public static void Execute() => Object.DontDestroyOnLoad(Object.Instantiate(Resources.Load("Systems")));
}

leaden ice
thick socket
#

not quite sure how it would cause the issue still

leaden ice
#

What script(s) are on the Systems object

#

PlayerInventory?

#

Show this line? PlayerInventory.SetPlayerStats () (at Assets/Scripts/Inventory/PlayerInventory.cs:212)

thick socket
#

oooh

#

I have it created in another spot also

thick socket
#

what Im finding says GameManager is null

leaden ice
thick socket
#

how could that happen if the only instance its created is inside GameManager?

leaden ice
#

I don't see any instance being created in GameManager. Are you talking about this?
playerInventory = new();

#

that's a giant red flag anyway

#

you cannot create MonoBehaviours with new

thick socket
thick socket
#

just a regular ol class

#
public class PlayerInventory
{
    public List<Items> ArmorList { get; private set; }
    public List<Items> WeaponList { get; private set; }
    public List<Items> JewelryList { get; private set; }
    //Helmet, Armor, Weapon, Jewelry
    public Dictionary<ItemType, Items> EquippedList { get; private set; }
    int gold;
    int gems;
    int xp;
    public PlayerInventory()
    {
        ArmorList = new();
        WeaponList = new();
        JewelryList = new();
        EquippedList = new()
        {
            { ItemType.Armor, null },
            { ItemType.Weapon, null },
            { ItemType.Jewelry, null },
            { ItemType.Undefined, null }
        };
        SetPlayerStats();
    }
leaden ice
#

gotcha. Looks like there's one being created in GameHandler too?

thick socket
#
using UnityEngine;
using System.IO;
using Assets.HeroEditor.Common.Scripts.CharacterScripts;
using Newtonsoft.Json;

public class GameHandler : MonoBehaviour
{
    string path;
    string json;
    public Character character;

    void Start()
    {
        //path = UnityEngine.Application.persistentDataPath + "/Inventory.json";
        //SaveInv();
        //LoadInv();
    }
    public void SaveInv()
    {
        PlayerInventory test = new();
        //json = JsonUtility.ToJson(test);
        json = JsonConvert.SerializeObject(test);
        Debug.Log(json);
        //Debug.Log(test.bag.Count);
        //Debug.Log(test.equipped.Count);
        File.WriteAllText(path, json);
    }
    public void LoadInv()
    {
        json = File.ReadAllText(path);
        //Debug.Log(json);
        PlayerInventory test = JsonUtility.FromJson<PlayerInventory>(json);
        test.EquipOnLoad();
    }
}


#

so it should only be created/happening inside gamemanager

#

(and shopEquipment which is in the scene)

leaden ice
thick socket
#
public void SetPlayerStats()
    {
        int hp = 500;
        int atk = 100;
        foreach (var item in EquippedList.Values)
        {
            if(item !=null)
            {
                hp += item.hp;
                atk += item.atk;
            }
        }
        if (GameManager.instance == null)
            Debug.Log("GameManager is null");
        if (GameManager.instance.player == null)
            Debug.Log("player is null");
        if (GameManager.instance.player.stats == null)
            Debug.Log("stats is null");
        GameManager.instance.player.SetStats(hp, atk);
    }
#

it throws error saying the GameManager.instance ==null

leaden ice
#

ok good

thick socket
#
public class GameManager : MonoBehaviour
{
    public static GameManager instance;
    public void Awake()
    {
        instance = this;
    }
    public void Start()
    {
        //could try 60 also for ex)
        Application.targetFrameRate = Screen.currentResolution.refreshRate;
        Scene a = new Scene();
        LoadSceneMode b = new LoadSceneMode();

        SceneManager.sceneLoaded += LoadState;
        SceneManager.sceneLoaded += FindPlayer;
        SceneManager.sceneLoaded += FindEnemies;
        LoadState(a, b);
        FindPlayer(a, b);
        FindEnemies(a, b);
        playerInventory = new();
        ExampleInvAdd();
        playerInventory.SetPlayerStats();
    }
#

if I have it called SetPlayerStats() here it works...if I have the SetPlayerStats() inside constructor it breaks

#

¯_(ツ)_/¯

#

disabled ExampleInvAdd() and it still works...thus nothing inside that should be helping "fix" it

leaden ice
#

look at this stack trace

#

GameManager.Start is not involved

#

Did PlayerInventory used to be a MonoBehaviour at some point in the past or something?

#

Somehow Resources.Load is directly calling the constructor 🤔

thick socket
#

not sure, it may have been at some point

#

GameManager has a public PlayerInventory playerInventory;

leaden ice
#

I wonder if your prefab doesn't have an orphan copy of the script on it still or something

leaden ice
#

this will do it

#

if its serialized

thick socket
#

but I don't have a =new() on it?

leaden ice
#

can you try making that [NonSerialized] for a minute

#
[NonSerialized] public PlayerInventory playerInventory;```
#

see if that changes anything

thick socket
#

that indeed does fix it thanks!

#

didn't realize if I just had it public it would auto-create a new()

leaden ice
#

Unity's serialization creates "empty" objects for all serialized fields

thick socket
#

good to know that [NonSerialized] is a thing to thanks!

wintry crescent
#

Hi, when I set rigidbody.centerOfMass=Vector3.zero, all child gameobjects with rigidbodies stop moving when the parent object moves - can this be remedied somehow? I need the centerOfMass to be zero, because otherwise when I rotate the parent object, the child objects are involved in calculating the center of rotation, which is not something I want

leaden ice
#

Why do you have child rigidbodies?

#

Typically you have one Rigidbody parent and then just colliders as the children

wintry crescent
leaden ice
#

assuming you want the small objects on the surface to treat the big object as their entire world

wintry crescent
leaden ice
#

Sounds pretty complex 😵‍💫 that could be done with proxy objects in the "internal" physics scene though

wintry crescent
leaden ice
#

Your game sounds complex 😜

#

I think you're going to end up with complexity either way here

distant owl
#

Hello, was wondering if anyone knew how to stop colliders from going through walls? Maybe cutting them off if that's even possible or somehow making sure if a player is directly in front of the collider but behind the wall anyone know any good tutorials for this or know how I would go about approaching this??

wintry crescent
#

or boxcasts

simple egret
#

(non-trigger) colliders won't go through walls as long as you move the object in a physics-friendly way

#

ie. using a Rigidbody

leaden ice
#

I assume this is for some kind of cone of vision kind of thing?

distant owl
#

actually yeah a raycast is something i didnt think about that

distant owl
distant owl
simple egret
#

So they'll go through walls

simple egret
#

Can't have both at the same time

distant owl
molten sandal
#

Question

#

RigidBody.velocity is in world space?

somber nacelle
#

yes

molten sandal
#

How to get the forward vector of object in local space?

tidal shadow
#

transform.forward

leaden ice
#

Forward is always Vector3.forward in local space

#

in world space it's transform.forward

molten sandal
#

and in local space?

leaden ice
#

that's pretty much the definition of forward

molten sandal
#

what about?

somber nacelle
#

Vector3.forward

leaden ice
#

aka (0, 0, 1)
barring floating point precision errors

mint tapir
static dew
#

Anyone know how to return if a section of a texture is masked or not? I'm using a raycast & renderer.material.GetTexture("_MaskTexture"), but I'm not sure how to differentiate if the raycast is hitting the masked area or not.

leaden ice
static dew
leaden ice
leaden ice
#

This one writes to the texture, you just want to read.

#

In fact if you're doing a Splatoon thing you should be somewhat familiar with these techniques already

fluid lily
#

What would you call stats more generically? Like math wise even. Like I am thinking something like compoundable or something. You have your base value, and then modifier values on that(like adding specific value, multiplying by specific values).

latent latch
#

stats

fluid lily
#

I find it is a pattern I use other places more generically, but I can't think of something to call it more generically then stats.

warm wren
#

Statistics

latent latch
#

EntityStatistics

leaden ice
fluid lily
#

I always think of Statistics as more finding logic/patterns in math, not the modification of numbers/values.

#

AugmentableValue like that one

fluid lily
leaden ice
#

ModifiableValue is what I use in my current project for a thing that has:

  • base value
  • additive modifiers
  • multiplicative modifiers
  • replacement modifiers
static dew
latent latch
#

I just have a class called BaseStat

fluid lily
#

I guess stats comes from dice times, where the outcome of actions is based on the likelyhood and combined values. Where in games it has more a meaning of just combined values.

#

Example: Your character has a statistically low chance of making that move work.

#

your stat, as it were, is too low

latent latch
#

DnD was always presented as ability scores, but lately people refer them as character stats

fluid lily
#

"There is no standard nomenclature for statistics; for example, both GURPS and the Storytelling System refer to their statistics as "traits", even though they are treated as attributes and skills."

#

I guess over all it is like the meaning for numbers in relation to an rpg, which does align with what I think of for statistics, but specifically what games call a stat would be attributes with modifiers mathmatically speaking.

#

"Bonus or base value"

#

Modifier makes more sense then Bonus, as I wouldn't consider a negative increase a bonus logically.

thin frigate
#

I'm trying to make a particle system (2d) that will generate particles from a point (bottom center) and have them fill the attached sprite. How should I go about doing this? Shape (Sprite) or ParticleForceFields seem like they could somehow be involved in this, but I don't know how

neon plank
#

Question, when using the NavMeshSurface, is possible possible to choose some layers to carve the nav mesh but not add? I.e: I want obstacles and walls to carve the nav mesh, but I don't want to have a nav mesh on top of a large box.

swift falcon
#

Using RealtimeCSG, I created a massive bounding box about 1 cubic kilometer in volume, with walls about 1m thick, to act as an "out of bounds" area, which would cause projectiles to disappear and players to die/teleport upon touching it, so that nothing deviates infinitely from the level.

However it seems many of my projectiles phase through this box, meaning they won't disappear at all. Is there anything I can do to improve this collision system?

leaden ice
swift falcon
# leaden ice 1. Make the walls thicker 2. reduce your fixed timestep 3. reduce your projectil...
  1. Make the walls thicker
    Alright, good... that was an idea I had... 🤔
  1. reduce your fixed timestep
    What do you mean?
  1. reduce your projectile speed
    No can do.
  1. increase your projectile collider size
    I may consider this. 🤔
  1. Use a simple BoxCollider instead and use OnTriggerExit to destroy the bullets
    A BoxCollider for what, exactly? The projectiles?

Also, I've been using OnTriggerEnter, so I'll try that. 🤔

swift falcon
leaden ice
#

there is no void

#

the idea with a box collider is they will always be overlapping until they are NOT

swift falcon
#

There is in my box.

leaden ice
#

at which point OnTriggerExit will be called

#

Then you know they are out of bounds

swift falcon
#

...

#

🤔

#

Huh.

#

So what you mean is have 'em always detect being within a big box, and when they're not in that box, they get despawned. 🤔

leaden ice
#

As for fixed timestep I mean this:

#

reducing it will mean physics simulation runs more frequently at smaller intervals of time

swift falcon
#

Interesting... 🤔

#

Is there a way I can check for layers akin to CompareTag?

leaden ice
#

in what context

swift falcon
#

Because it seems some of the generated meshes do adopt the necessary layer, but not the necessary tag.

#

Which means CompareTag may not be useful. 🤔

leaden ice
#

I'm not sure I follow this conversation anymore

swift falcon
#

🤔

leaden ice
#

If you're trying to limit the OnTriggerExit to certain layers, you should use the layer based collision matrix in physics settings

swift falcon
#

Ok, so what I attempted to do with OnTrigger[Enter/Exit] was to see if it was in contact (or not) with a GameObject with the "Out Of Bounds" tag.

polar marten
leaden ice
#

you can do this still - or use layer based collisions to prevent other interactions

polar marten
#

if you need a bounding box, create a game object with 6 box colliders

#

do not try to use a mesh with a void in the middle as a physics mesh

#

it is physically invalid

#

does that make sense @swift falcon ?

#

you cannot use a mesh generated this way with realtimecsg (which i am familiar with) for the purpose you want

#

period full stop

swift falcon
#

So, bounding box ought to be a simple set of box colliders.

polar marten
#

that's correct

swift falcon
#

Ok.

polar marten
mystic ferry
#

I love you guys

neon plank
thin frigate
polar marten
thin frigate
#

There may be a way to use emission from texture to work, but it creates a weird effect I'm not a fan of right now

polar marten
#

maybe ask vfx and particles

neon plank
polar marten
#

you can use different geometry for navigation than for rendering

#

you can also specify navigation area as non-navigable i believe

#

lots of easy fixes

#

read the docs

neon plank
polar marten
#

don't remember exactly

polar marten
#

use the docs

neon plank
#

That doc is about the old workflow.
I'm using the component based workflow...
I know I could add NavMeshModifier to each obstacle. But I wanted to know if there was a simple solution layer-wide.

polar marten
#

i think you add navmeshmodifier to each obstacle

neon plank
#

Ok

polar marten
# thin frigate I don't want to create the particles in the shape of the texture, I want the par...

This is a tutorial on using the Vector Field Asset for Unity which creates a vector field (aka 3D Texture) which can be used in the Visual Graph or in the Particle System Force Fields to apply force to the particles based on each pixel of the texture

Checkout my assets for more Tuts!
------------------------------------------------------------...

▶ Play video
faint brook
#

any ideas on how to increase randomness i have the following ```c
agent.transform.localPosition = new Vector3(Random.Range(-2f, 2f), 4f, Random.Range(-2f, 2f));
Random.InitState((int)System.DateTime.Now.Ticks * 123);
block.transform.localPosition = new Vector3(Random.Range(-2f, 2f), 4f, Random.Range(-2f, 2f));
Random.InitState((int)System.DateTime.Now.Ticks * 321);
goal.transform.localPosition = new Vector3(Random.Range(-2f, 2f), 3, Random.Range(-2f, 2f));

#

but this seams to keep them relativly together

#

also only spawns in the top half of the parent

leaden ice
#

Why are you setting the state of Random manually?

#

There's no need for that

#

Unless you're doing some kind of seeded deterministic thing

faint brook
#

no I am not I just read that that can help

leaden ice
#

Also casting Ticks to an int is going to end up truncating probably

#

So you're likely setting the seed identically in both those calls

#

Hence non randomness

#

They're spawning at the top because you're using constant y positions, no?

faint brook
#

by top half I mean from a birds eye sorry for the confusion

#

as you can see the objects spawn close to each other especially the blue and the green(in this case)

leaden ice
#

well you're only spawning within this -2, 2 range

#

that's not very far

#

And depending on the scale of the parent object it may be even smaller

faint brook
#

I was under the impression that -2f , 2f was the range of the parent?

leaden ice
#

huh?

#

wdym by that

faint brook
#

when I set it to -10f 10f (the size of the parent) it always spawns out side

leaden ice
#

I don't know what to say

#

it's just a random position between -2 and 2

#

it has nothing inherently to do with the size of the parent

#

(other than being affected by its scale, since it's local position)

faint brook
#

oh 🤦‍♂️

leaden ice
uncut tundra
#

Anybody tell me why i have to hit the spacebar multiple times before i actually jump

`using UnityEngine;

namespace Com.HighFiveGamesStudio.GetYoGuns
{

public class Motion : MonoBehaviour
{
    
    //Variables

    public float speed;
    public float sprintModifier;
    public float jumpForce;
    
    public Camera normalCam;

    private Rigidbody rig;
    
    private float baseFOV;
    private float sprintFOVModifier = 1.5f;

    private void Start()
    {
        Camera.main.enabled = false;
        baseFOV = normalCam.fieldOfView;
        rig = GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        //Axles
        float t_hmove = -Input.GetAxisRaw("Horizontal");
        float t_vmove = Input.GetAxisRaw("Vertical");
        
        
        //Controls
        bool sprint = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift);
        bool jump = Input.GetKeyDown(KeyCode.Space);
        
        
        //States
        bool isJumping = jump;
        bool isSprinting = sprint && t_vmove > 0;
        
        
        
        //Jumping
        if (isJumping) 
        {
            rig.AddForce(Vector3.up * jumpForce);
        }
        

        //Movement
        Vector3 t_direction = new Vector3(t_vmove, 0, t_hmove);
        t_direction.Normalize();
        
        `
#

`float t_adjustedSpeed = speed;
if (isSprinting)
{
t_adjustedSpeed *= sprintModifier;
}

        Vector3 t_targetVelocity = transform.TransformDirection(t_direction) * t_adjustedSpeed * Time.deltaTime;
        t_targetVelocity.y = rig.velocity.y;
        rig.velocity = t_targetVelocity;
        
        
        //FOV
        if (isSprinting) 
        {
            normalCam.fieldOfView = Mathf.Lerp(normalCam.fieldOfView, baseFOV * sprintFOVModifier, Time.deltaTime * 8f);
        } else 
        {
            normalCam.fieldOfView = Mathf.Lerp(normalCam.fieldOfView, baseFOV, Time.deltaTime * 8f);
        }
        
    }
}

}`

faint brook
leaden ice
mystic ferry
#

man I feel like I could spend a lifetime learning this engine and still barely understand it

#

I've been studying it like CRAZY for over 3 years and I still see shit I've NEVER seen before to this day

leaden ice
mystic ferry
#

I guess, but you'd figure it'd slow down eventually

#

I haven't even touched any of the DOTS stuff yet. And that's probably a huge rabbit hole

swift falcon
#

Does scaling a game object also scale any colliders attach to it and its children?

swift falcon
#

Interesting.

#

Cool. 😄

leaden ice
#

Note there are some caveats to that when it comes to colliders. SphereCollider is always a sphere, even if you try to "skew" it with a weird scale. Similar restriction on CapsuleCollider

swift falcon
leaden ice
#

something like that. I don't remember exactly

swift falcon
#

k

leaden ice
#

maybe the smallest, maybe the largest 😉

swift falcon
#

lol

thin frigate
#

Realistically, how much of an impact of performance do public references have? I've always been taught that avoiding unnecessary public references is good practice, but if my game is having performance issues how likely is it that they're the cause?

leaden ice
#

Use the profiler to diagnose your performance issues

thin frigate
leaden ice
#

the tool designed to diagnose performance issues

thin frigate
#

Alright better question, where's that

mystic ferry
#

google is a thing you will need to use a lot if you have any hope of creating a game

cosmic rain
cosmic rain
mystic ferry
cosmic rain
#

Readability, extendability, debuggability.

mystic ferry
#

but you'll write trash code in the beginning no matter what which is to be expected

#

you have to understand what's wrong with bad code by writing some before you can understand how to avoid/fix it

#

people can tell you it's bad all they want but until you understand it from personal experience I doubt it'll really do anything

#

just my two cents

swift falcon
#

Hmm, looking for some help if anyone can provide a bit of feedback! Context: moving rigidbodies while simultaneously applying velocity (moving platforms, but learning what's wrong will help me with a lot I'm sure)

Currently my character controller is a rigidbody2d controller that adds force to the player in fixedupdate depending on inputs.
The platform script is detecting rigidbodies on collision and then using transform.translate to move them (in lateupdate). It uses the platform's stored last position and current position to figure out what to do.

The problem currently is the platform causes visual jitter to everything riding on top of it, and there's definitely something wrong.
I mostly understand what's going on, but the specific details of the issue feel like I'm not quite grasping ahold of enough info to figure out what I need to change. If I had to take an educated guess I'd probably think it was related to a number of things including when I'm calculating/moving the RB, as well as potentially needing to lerp the values or something... A bit clueless though.

If anyone has resources to guides on the topic that are better than the random youtube info I keep stumbling into, and can point me in the right direction (or can tell me straight up what the problem is) I'd be grateful

swift falcon
#

this is a different approach I tried, using parenting the object (player in this case) to the platform on collision

#

it works a lot better, and seems to be fine, save for the issue of some persistent jitter I can't get rid of

potent sleet
#

dont use translations for rigidbodies

swift falcon
#

see I'd heard not to before, and then every tutorial or post on a forum goes "translate it lol"

#

I feel insane

potent sleet
#

if you want your props to move with the platform you could potentially use joints or make it kinematic with parenting

mystic ferry
#

translations completely avoid the physics engine so no collisions, shit can warp through walls etc

swift falcon
#

right,

#

so what would a best practice be for moving platforms carrying rigidbodies/the player

#

exerting additional forces?

potent sleet
#

I told you a few options

swift falcon
#

I'll need to look into joints. Making it kinematic doesn't sound like it will work for me though, since I'd want it to continue to function as a dynamic object

#

I'm not really sure though. I'm reaching a point where I wonder "Should I just code everything as kinematic?"

potent sleet
#

kinematic can be toggled on and off

#

such as OnCollision with player or something

swift falcon
#

I'm trying to imagine what I'd need to change in the controller to accommodate a shift to kinematic

#

there

#

may not be issues, now that I think about it

#

thanks, it's something to think about for the moment

potent sleet
swift falcon
#

2d colliders, I'm rendering 3d meshes but the game is using 2d for everything

#

this way I can do funny things with lighting and animation

potent sleet
swift falcon
#

like, a platform with it's own rigidbody and force to move location?

#

no I have not

potent sleet
swift falcon
#

correct

potent sleet
#

thats what I meant when i said kinematic

#

but that would require diff movement than addforce

swift falcon
#

I'm just generally confused now. So, did you mean change the player to kinematic to match the platform? Or did you originally mean make the platform kinematic

#

if I make the player kinematic at any point I've got to use some different method to move them, since force can't be applied to kinematic objects, correct?

potent sleet
swift falcon
#

the player is an RB2D

#

dynamic objects for physics based interactions I wanted to be rigidbodies

potent sleet
swift falcon
#

alright

tawny mountain
#

Not sure where to post this
But
What is the easiest way to set up player data recovery when using firebase firestore?

leaden ice
#

"player data recovery" is a vague and probably complicated subject

#

you'd have to explain exactly what that means in the context of your game

mystic ferry
#

does anyone know what retail disks and gold master disks are? this is the steamworks sdk docs

#

it just kinda uses the terms like everyone knows what they mean, and I can't find anything about it anywhere

potent sleet
#

disks ? what is this 2007

mystic ferry
#

I'm pretty confident they don't mean physical disks? but I don't know

#

not sure what else they would mean

#

nevermind. Maybe that's exactly what that means

#

"A final version of software ready for release to manufacturing"

potent sleet
#

some form of protection?

#

i think has to do with DRM stuff

mystic ferry
#

this is the docs if you're curious

#

maybe I'm just stupid lol. Can't really figure it out

potent sleet
#

I think it's literally what I said lol

#

has to do with putting your game on disk and auto install from steam or something

#

i think

thin frigate
#

Is checking if( GameObject.GetComponent<T>() != null ) significantly more performance intensive than implementing a Tag system for type T and using that?

potent sleet
mystic ferry
#

interesting

potent sleet
#

just a disk?

mystic ferry
#

I didn't even know that was a thing

potent sleet
#

The Steamworks SDK includes a customizable installer that you can include on your gold master. The installer is designed to help users install Steam and begin loading your game as quickly as possible. The installer has also been designed to ensure compatibility with the installation portion of the Games for Windows certification.

#

like if you create special edition probably with art and shit

mystic ferry
#

steamworks docs try not to be impenetrable challenge difficulty impossible

#

thanks king @potent sleet

cosmic rain
#

But get component is not that heavy.

thin frigate
#

I just mean using tags instead of GetComponent

potent sleet
#

it's always better to use types than strings imo

swift falcon
potent sleet
#

strings aren't type safe and very brittle @thin frigate

swift falcon
#

yeah it literally just works this way and idk why anyone ever was telling me to do it differently

mystic ferry
#

if you're caching component references it shouldn't even matter

swift falcon
#

kinematic platform moved with force

potent sleet
cosmic rain
#

But the difference is probably negligible

thin frigate
#

Alright

#

I'm trying to optimize my code to deal with having even a handful of projectiles in the scene at once, and it's being difficult.

mystic ferry
#

I always say bro optimize geometry and draw calls

#

ain't no way the fraction of a millisecond you save avoiding the lightning fast GetComponent calls are going to put a noticeable dent in anything

#

plus use the profiler anyway

thin frigate
#

This is a 2d Asteroids clone, I'm not sure how applicable that is here

mystic ferry
#

then performance is a nonissue

thin frigate
#

also I don't want to be assed to wait 20 minutes for a build

#

It IS an issue, though, that's the issue.

mystic ferry
#

what does the profiler say

thin frigate
#

Like I said, I don't want to wait for a build

#

I probably should, but

mystic ferry
#

what does that even mean

#

the profiler doesn't need a build

thin frigate
#

It doesn't?

polar marten
mystic ferry
#

I don't even know if you CAN use the profiler in a build, it's in the engine

polar marten
swift falcon
#

I have not

#

I'll give that a look

mystic ferry
#

Window -> Analysis -> Profiler

thin frigate
thin frigate
#

This I guess

mystic ferry
#

spend some time learning how to read the profiler

#

it's going to be much more useful figuring out where you're writing inefficient code that way then just guessing at optimizations that might not even do anything

#

it'll even show you how much memory different things are using. It's extremely useful

potent sleet
#

look up tutorials

thin frigate
#

already on it

swift falcon
thin frigate
#

Alright apparently around 85% of the performance was being taken up by drawing gizmos. not very cool.

mystic ferry
#

there you go

tawny mountain
# leaden ice you'd have to explain exactly what that means in the context of your game

I currently have players anonymously authenticating with firebase , then they can choose to link with facebook.. I save the players data on firestore naming the doc the players uid.. now if my player clears local data and gets back in to the game a new anonymous auth is created and when logging in to Facebook again it tries to re-link to the new account , I'm unable recall the players originally assigned uid.. I'm currently working on a solution by trying to save email and uid on realtime Database

swift falcon
#

Hrmm, if addforce works on kinematic objects.. addtorque should as well, right? in order to rotate it.
I just wanted to test rotating a kinematic platform in place.

#

given it's a 2d rigidbody, this should be all it takes, I believe

dusk apex
#

Forces shouldn't work on kinematic objects. Guessing you meant non-kinematic objects.

swift falcon
#

Oh sorry, I see

#

I'm confusing velocity and force

leaden ice
swift falcon
#

what's the term for the velocity equivalent for rotation? is there one?

leaden ice
swift falcon
#

I am in 2d

tawny mountain
swift falcon
wild nebula
#

I am getting lags everytime I swap audio and AudioSource.Play() different musics, what are some good ways to reduce this?

#

Like what are the ideal settings for music, sound effects, etc?

#

Just preload and load in background enabled for all musics? Will that take a lot of memory?

tawny mountain
# leaden ice Yes you need to associate the email or Facebook account with your user account t...

this is what i get (the email will fill in when player signs in with facebook) ... See how it has double values both inside and outside the players document? then I need ti get tit to wokrk only when player logs in with facebook
my script
https://pastebin.com/y247szEe

#

this is what im looking for

sterile zealot
#

Can someone show me how to post code in here? I've done it before so I know it needs to be done, but it's been so long I forgot the syntax.

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.

sterile zealot
#
{
    // Game Initializations
    public TMP_Text moneyText;

    int money = 5000;

    // Main Game Start
    void Start()
    {
        moneyText.text = "$" + money.ToString();
    }```
#

My code runs but causes the play to pause and I have to unpause it each time.

#

I'm also getting this error message and not sure what I need to do here to resolve that. "NullReferenceException: Object reference not set to an instance of an object
GameManager.Start () "

sterile zealot
#

And under the Inspector, yes I have the TMP_Text linked to MoneyText

#

@dusk apex NullReferenceException: Object reference not set to an instance of an object
GameManager.Start () (at Assets/Scripts/GameManager.cs:25)

sterile zealot
#

This line in Start() moneyText.text = "$" + money.ToString();

dusk apex
#

Money text is null

sterile zealot
#

I'm not sure how to resolve that

dusk apex
#

Make sure you've assigned it in the inspector

sterile zealot
#

I have for sure that

#

It's also updating the text when it runs

leaden ice
sterile zealot
pure flint
#

I made a List/Array and I wanted to reference all child gameObject in parent into the List/Array automatically by script I couldnt figure out how. Anyone got ideas?

#

without find tag if possible

leaden ice
pure flint
sterile zealot
#

@dusk apex Would my code update the text, if it wasn't assigned under Inspector?

pure flint
#

like List<GameObject> those stuff

tawny mountain
sterile zealot
#

I've seen where this might be related to not have an instance, but it's a single player game and only one Money UI text field. Do I really need to do a search/find on the name of my TMP_Text?

pure flint
#

uh yea I know cause they're almost the same thing except List is more flexible

pure flint
#

with list

tawny mountain
#

Make it public and drag and drop it in the inspector

sterile zealot
tawny mountain
dusk apex
#

If it's not assigned, accessing the text property of the tmp component will throw an NRE.

leaden ice
tawny mountain
#

Make the variable public and drop the game object in to the slot

sterile zealot
#

This is what is throwing me off because I have it assigned here underlined in red

leaden ice
sterile zealot
leaden ice
#

No

#

All of the GameManagers

tawny mountain
celest pendant
#

hello

dusk apex
#

Debug.Log($"{name} has this script", gameObject);

celest pendant
#

I am newbie, which projects do you suggest me to learn unity? I can use c# and unity well.

tawny elkBOT
#

🧑‍🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

sterile zealot
leaden ice
celest pendant
#

@leaden ice I have completed unity learn 2d ruby game doc. It was awesome and I have learnt awesome things. Yet, I like to build something from scratch by my own self. What do you suggest me to build ?

sterile zealot
#

Canvas and Canvas->UI->MoneyText are the only two things in my scene that call to GameManager at the moment

leaden ice
#

Find all the GameManagers in the scene

#

Delete the extra copy you forgot about

tawny mountain
#

Make data recovery

sterile zealot
#

That has the Script GameManager in it

#

Under Inspector

leaden ice
#

Find all of them

#

You really should only have one

#

Fix any without a reference set

#

Or delete it if not needed

sterile zealot
#

Sorry PreatorBlue but I'm not sure what you mean by having multiples

leaden ice
#

You have that script attached to multiple objects in the scene

#

Find them and fix it

dusk apex
#

In start preferably

sterile zealot
#

@dusk apex Yes. I got just this

#

MoneyText has this script
UnityEngine.Debug:Log (object,UnityEngine.Object)
GameManager:Start () (at Assets/Scripts/GameManager.cs:26)

dusk apex
sterile zealot
#

Correct

leaden ice
sterile zealot
leaden ice
#

Maybe you have the script on that one object twice

sterile zealot
#

Okay.. Take made me think of something. I did have it also listed under the parent Canvas object

#

I unticked it and error goes away

leaden ice
#

...

dusk apex
#

Try logging the value of the money text component cs Debug.Log($"{name}'s component for money text was : {(moneyText != null ? "Not Null" : "Null")}");

sterile zealot
#

I'm still getting use to Unity, so it one script per object?

leaden ice
#

It's as many as you want but it needs to make sense

#

Anyway the log wasn't printing because you put it after the code with the error

dusk apex
#

Ah, so there were two.

leaden ice
#

Yes

sterile zealot
#

Okay, so if I have more than two references to the same script in a scene I need to do the search/find?

leaden ice
#

Irrelevant

#

The number doesn't matter

#

You have to assign your references that's all

deep willow
#

im looking into doing pathfinding on a grid, but i need to find the nearest enemy on the grid while moving around allied units. can i use pathfinding to find the nearest enemy then actually follow that path?

sterile zealot
#

Well my code hasn't change just the references

deep willow
#

i cant just find the nearest enemy in a range

rigid island
sterile zealot
#

So what would be the Correct way if I had it with two references?

leaden ice
deep willow
#

i need to find the nearest enemy that is the fastest to get to

leaden ice
#

You didn't assign one of them

sterile zealot
#

Ah... that's making more sense now

dusk apex
sterile zealot
#

Yeah that second one is showing up but nothing is assigned so it's showing NULL

#

Ugh.. so dumb when you know what's going on

dusk apex
#

If you've got two instances in the scene, each instance must have their fields properly set before using their fields else you'll get NREs

sterile zealot
#

I just updated this code to get it working tonight, so left out something PraetorBlue was right

rigid island
leaden ice
#

A* is for pathfinding

sterile zealot
leaden ice
#

To find the nearest enemy you would use Dijkstra's

dusk apex
#

When you drag something into the field, that field now references what's been dragged in via inspector.

deep willow
#

can i ask A* to find the nearest enemy taking into account allies? then move to that enemy?

leaden ice
#

Or just depth first search

#

A* is for navigation to a known destination

deep willow
#

yeah thats what i thought

sterile zealot
#

Now that I'm on this side of understanding the problem, it's a really basic and dumb mistake..

deep willow
#

i need to search for the destination then pathfind to it

leaden ice
#

Dijkstra's algorithm will give you both the nearest enemy and the shortest path to that enemy

deep willow
#

ah okay

#

Breadth First Search will find the fastest distance to any enemy?

rigid island
#

!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
rigid island
#

I see you took some inspiration from my code ? @long totem

long totem
#

I think I copy & past somewhere else months ago XD

#

Last time it worked fine

#

I just dont know how it stop working suddenly

rigid island
long totem
#

the capture screenshot button here

#

Normally It wont be grey right?

rigid island
leaden ice
long totem
#

Oh

#

So, uh the problem is I couldnt capture the rendered screenshot

rigid island
#

in what sense ?

#

code errors or what

long totem
#

And I just noticed the classes are not green

rigid island
#

you might need to configure your VS then

long totem
#

those under public class

rigid island
long totem
#

Is there a length requirement for posting codes?

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

long totem
rigid island
long totem
#

It wont capture the the screenshot when I click "camerainfo"