#archived-code-general

1 messages · Page 434 of 1

hard estuary
#
  1. Scroll to the top of your script.
  2. Find the namespace you want to delete.
  3. Select its text.
  4. Press delete of backspace.
steady bobcat
#

this lil guy

#

UnityEngine.Vector2 AND System.Numerics.Vector2 exist 🤯

ripe bloom
#

Thanks for the response! I'll look into how coroutines work and try to find a solution like the one you suggested. your option B didn't make sense to me as I am relatively new, I don't see how I could store the info you're talking about in a bool. So I'll try option A for now. Again thanks for the response!

hard estuary
hard estuary
ripe bloom
rigid island
#

System.Numerics contains Vector2 and UnityEngine also has Vector2.

#

the computer has no idea which one you want

copper lodge
#

so I have to delete them?

rigid island
#

in this case you wouldn't want the one from System.Numerics, VisualScripting one can be deleted too cause thats not even being used, hence the grayed out text

copper lodge
#

ok thank

lapis pendant
#

Anyone here knows how to make recording cameras? like content warning does? i know few APIs, but they're all paid, is there any free option?

hard estuary
#

@copper lodge I will also add, that Visual Studio automatically adds namespaces as used ones whenever you try to use something that could belong to this namespace. In this case, you used Vector2, and your code editor noticed that the namespace was missing, so it added one. While this feature is convenient in most of cases, sometimes it adds the wrong namespace, if there is more than one potential candidates. This feature probably can be turned off in settings.

rigid island
#

iirc it adds the first alphabetical one right ?

hard estuary
copper lodge
#

ok thank you very much everyone I'm new and French too so I had trouble but thank you very much, is it good like that?

vestal vector
#

Carrying objects in Unity first person. Help please!

dawn nebula
#

Hey I'm using Unity 6 and it seems like Cinemachine has changed up a lot of its scripts.

#

How do I get a simple follow/look at where I can specify a tracking distance

rigid island
dawn nebula
inner geyser
#

this is my current speed control and moveplayer code, i want to make it so that instead of slowing the player while grounded if they are over the movement speed, it just prevents them from accelerating with movement keys

#

how would i do that

vestal arch
inner geyser
#

yes

#

i want the player to reach the max speed i set if they hold w, but if they recieve external force, they wont instantly drop to the max speed

vestal arch
#

i mean even with just holding w you can get inconsistent max speeds

inner geyser
#

how inconsistent

vestal arch
#

hmm not sure

inner geyser
#

the way it currently is, the instant you touch the ground, it drops your speed, i want basically anything besides that

vestal arch
#

actually MovePlayer is called from FixedUpdate, right?

#

it should, given the AddForce with Force

vestal arch
#

since the deltaTime is consistent i think that wouldn't be too much of an issue

#

originally i was thinking about framerate affecting the acceleration step size

#

but that won't be an issue

inner geyser
#

if (flatVel.magnitude >= moveSpeed)
{
dont addforce

#

this is basically what i want

vestal arch
#

there will still be some inconsistency with different friction or drag perhaps... that could end up jerky, but ig you'll have to test for that

inner geyser
#

but i dont know how to put it in

vestal arch
#

you can't undo an action

#

well i mean you can with AddForce but you shouldn't, for the sake of your future self

vestal arch
inner geyser
#

i just want it to prevent rb.AddForce from doing anything

vestal arch
#

you can't

#

but you can choose to not AddForce at all

#

invert your condition; only if your speed is under the cap, then do addforce

inner geyser
#

im very new to c# so idk how i would format

vestal arch
#

do you not understand conditionals?

inner geyser
#

i do

vestal arch
#

you're already using them in your code

vestal arch
inner geyser
vestal arch
#

if (speed < cap) addforce(x);, put it in a block if you want, substitute in the proper values and variables

inner geyser
#

ok ill try that

#

one momment

vestal arch
#

if you have further questions, consider asking there

inner geyser
eternal gorge
#

Hi all, I'm trying to set up a parallax script with infinite scrolling but I'm getting an error that "length" does not exist in the current context

#

I'm using Unity 6 (6000.0.40f1)

somber nacelle
tawny elkBOT
eternal gorge
#

Oh right I forgot to add the variable 🤣

#

Thank you lol

shadow wagon
#

what is a typical way people make a wraparound map? so on a plane I start at A, go to the left side to end up at B, then go up to the top and end up at C.

i dont think it would work if I just teleport the position from A to B, B to C, becuase I have a rigidbody character, it doesnt really work all that well if I did an instant position change over a distance

thorn ibex
#

Can't you use RB.MovePosition?

shadow wagon
#

maybe, but I imagine there could be issues if i was to do it with teleporting. like a trail renderer would end up creating a massive streak across the map, and enemy targetting would head towards the left edge, then theyd do a 180 to head to the right edge

mellow sigil
#

MovePosition does interpolation so it won't work here

shadow wagon
#

if it makes it any easier, I'm probably only going to let you move to A-B there isnt going to be B-C for the top wrap around

mellow sigil
#

Have you already tried doing teleporting with position change or are you just anticipating issues?

shadow wagon
#

I'd used teleporting for the player before when I wanted to set the spawn point, hadnt realised you could do MovePosition, so I had a pretty hacky thing of setting its body to kinematic, teleport, then lateupdate set it back to non kinematic

thorn ibex
#

For the enemy AI, you're just going to have to hard code that such that enemies can also wrap around

#

It's going to look jank otherwise

shadow wagon
#

thing is if its just wrapping around from left to right, that means the map is just a cylinder

#

I dont know if its really possible, but if I could make it so driving in one direction basically is like an infinite series of squares, youd end up always returning to 0,0

thorn ibex
#

You could just use a cylinder as the map

#

And map a 2D sprite onto the 3D object

shadow wagon
#

unfortunately my vehicle controller doesnt really work in 3D, its only really designed for a 2D surface

#

it is something I'd thought of doing

#

ill do some research and see if anyone has solved a similar thing to this

young tapir
#

Is there an accurate readout for the tension a joint is under? Right now I'm just checking currentForce and I've tried it with torque and can't see another reasonable field for it. Currently this is logging as 0 so I assume this is force as in AddForce and not close to what I want 😅

        while (jointEffect.configurableJoint.currentForce.magnitude < 0.5f)
        {
            Debug.Log($"Waiting: {jointEffect.configurableJoint.currentForce.magnitude}");
            yield return new WaitForEndOfFrame();
        }```
crisp flower
#

I have a tech tree in my game. well, at the moment more of a group of techs with a few dependencies. It's all working on the back end, unlocking things changing stats etc.

I need to make a front end for it though. I have a canvas where I intend to do this.... but not really sure how to handle a techtree that exists as a set of scriptable objects. totally open to using an existing solution rather than reinventing the wheel

steady bobcat
young tapir
#

I'll try to 6 decimal places maybe, It does seem to be under a lot of tension in game which is why I'm a little confused

steady bobcat
#

is it bigger than float.Epsilon?

young tapir
steady bobcat
#

then is zero for real 👍

young tapir
#

Any ideas as to how I can fix it? I know it's too low to work with already haha

I'll take that as a no, then. I'll just use rigidbody.Velocity 🙃

hexed pecan
#

Like is there anything that should make it use force

young tapir
vestal arch
waxen matrix
#

Is it true that referencing Transform instead of GameObject is cheaper? And should i use it instead?

#

I was always using GameObject

vestal arch
#

And should i use it instead?
not for this reason, no. use what makes sense

#

computers are fast

#

a little indirection won't have any effect

#

don't worry about optimization until it becomes a problem

#

in general, you usually shouldn't reference GameObject since it's not super useful on its own. use a type corresponding to what you do with said object
if you follow the transform, referencing the Transform directly would make more sense
if it's an enemy and you want to interact with a script, reference that script
etc

waxen matrix
#

Okay, Thank you!

hard estuary
waxen matrix
#

Its just that, im working with some source, and it references prefabs as Transform...

vestal vector
#

Can someone help me with carrying game objects in first person? I have a Thread created with all the information. Thank you so much!

hard estuary
# waxen matrix Its just that, im working with some source, and it references prefabs as `Transf...

I think the main downside of such approach is that you won't see any prefabs in your Asset list (it's because for sake of performance Unity doesn't open them all to scan their components). Drag-and-drop works fine though. In the past I was sometimes losing references to prefab components, and I'm not sure what could cause it. I don't have such issue lately, so it could be some bug in older version of Unity. I often add references to my own components, making it easier to initialize things without using GetComponent, and it also prevents me from using a prefab that doesn't have such component.

waxen matrix
#

Hmm, ill think about it, thanks again!

ebon jacinth
#
using UnityEngine;
using TMPro;

public class Movement : MonoBehaviour
{

    public Rigidbody rb;
    public float Walkforce;
    public float Climbforce;
    public float Descendforce;
    public TMP_Text TimerText;
    public TMP_Text SpeedText;
    private float playerSpeed;
    private bool isTimerRunning = false;
    private float TimerTime = 0.00f;

    void FixedUpdate() {
        if (Input.GetKey("a")) {
            rb.AddForce(-Walkforce, 0, 0);
            isTimerRunning = true;
        }

        if (Input.GetKey("d")) {
            rb.AddForce(Walkforce, 0, 0);
            isTimerRunning = true;
        }

        if (Input.GetKey("w")) {
            rb.AddForce(0, Climbforce, 0);
            isTimerRunning = true;
        }

        if (Input.GetKey("s")) {
            rb.AddForce(0, -Descendforce, 0);
            isTimerRunning = true;
        }
        
        if (Input.GetKey("m")) {
            isTimerRunning = false;
            TimerTime = 0.00f;
        }

        if (isTimerRunning == true) {
            TimerTime += Time.fixedDeltaTime;
        }

        playerSpeed = Mathf.Abs(rb.linearVelocity.z);
        Debug.Log(playerSpeed);

        TimerText.text = "Time - " + TimerTime.ToString("F2");
        SpeedText.text = "Speed - " + playerSpeed.ToString("F2");
    }
}

guys why is playerSpeed 0 when the cube is moving?
all the script works so it's not an issue, but playerSpeed is 0, thus SpeedText is 0, please help

vestal vector
#

Since I got buried again: can someone please help me with carrying objects in first person?

I have a very detailed explanation on a thread. I linked my code properly as the rules advise. It’s formatted nicely. Please I need some help!

thin aurora
#

Please link it

#

You can bump your questions when they have not been answered

vestal vector
ripe bloom
#

I am trying to manually trigger OnDrop from another script, but it's not working. I am wondering what I am doing wrong.

I am trying to trigger OnDrop from the OnPointerUp function in OnEmotionInvClick. This is to trigger the OnDrop function in EmotionDropHandler.
EmotionDropHandler script: https://paste.mod.gg/ngqviaqxnxiz/1
OnEmotionInvClick script: https://paste.mod.gg/ngqviaqxnxiz/0

I am getting the error:
"NullReferenceException: Object reference not set to an instance of an object
EmotionDropHandler.OnDrop (UnityEngine.EventSystems.PointerEventData eventData) (at Assets/Scripts/EmotionDropHandler.cs:22)"

I am not sure if I've used the syntax correctly, and there is little to no documentation on triggering OnDrop from another function.

steady bobcat
#

its not really related to your main question

ripe bloom
steady bobcat
#

btw doing get components all the time is not good, get once and keep a ref and work with the script type instead of GameObject

#

clearly not if its throwing a null ref exception 😐

#
MyClass c = null;
c.DoThing(); //NullReferenceException will be thrown!
#

(i am going off the line numbers in the pasted code btw)

ripe bloom
# steady bobcat (i am going off the line numbers in the pasted code btw)

It's not throwing a null ref exception to finding the canvas, the error is in the EmotionDropHandler script. The error is relating to this line of code:
Debug.Log("Drop info| Dropping on: " + gameObject.name + " | Object dragged: " + eventData.pointerDrag.name);
Also I will not completely rewrite my scripts to remove all the GetComponents as the project is very nearly finished, and I want to move on haha.

steady bobcat
#

ah you miss labelled the links

#

then either gameObject is null, eventData is null or eventData.pointerDrag. Im guessing eventData.pointerDrag.

ripe bloom
#

Huh, the link itself is correct but when I click on it, I am taken to the other script for some reason.

ripe bloom
steady bobcat
#

i guess we can presume the drag ended so this is no longer set

ripe bloom
steady bobcat
#

Oh right i remember. Perhaps it would be better if you you have containers to hold these objects so the use can drag one out. You can then create a new one in the container when the drag begins.

#

may be simpler vs trying to transfer the input to another new object as it seems its not exposed for us to modify easily on an event system

#

The container is to make sure layout is not messed up by this

ripe bloom
#

Could be a good idea, but I think I'd need to rewrite some scripts. I think I'll just try to find a way to do a raycast to check for objects underneath

swift falcon
#

how would i go about making this code work where isnted of using raycasting to find the grapple point i throw an object that attaches to a surface

#
using UnityEngine;

public class puzzle : MonoBehaviour
{

    [SerializeField] private float grapplelength;
    [SerializeField] private LayerMask grapplelayer;

    private Vector3 grapplePoint;
    private DistanceJoint2D joint;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
       joint = gameObject.GetComponent<DistanceJoint2D>();
        joint.enabled = false;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit2D hit = Physics2D.Raycast
                (
                origin: Camera.main.ScreenToWorldPoint(Input.mousePosition),
                direction: Vector2.zero,
                distance:Mathf.Infinity,
                layerMask: grapplelayer
                );

            if (hit.collider != null)
            {
                grapplePoint = hit.point;
                grapplePoint.z = 0;
                joint.connectedAnchor = grapplePoint;
                joint.enabled = true;
                joint.distance = grapplelength;
            }

            if (Input.GetMouseButtonUp(0))
            {
                joint.enabled = false;
            }
        }
    }
}  ```
steady bobcat
ripe bloom
steady bobcat
#

I often realise I need to refactor something but don't have the time but sometimes it becomes essential to refactor to resolve a critical issue/flaw

ripe bloom
#

So thank you but I'm going to google raycasting now

#

and I'll cast that ray

steady bobcat
#

up to you what you do and if its just for you/ some student assignment then if it works its probably good 😆

ripe bloom
#

It was just an idea I had on a whim to make a game I could actually complete this time around, (Just a prototype/10 min game) I've learned a lot but it was a bit above my skill level. So I'll be using that ray cast as a duct tape, and thanks for the link!

copper lodge
#

I think the problem comes from the code? but I can no longer launch the game

somber nacelle
#

you need to get vs code configured 👇 !IDE

tawny elkBOT
rigid island
somber nacelle
covert dust
#

Hey there, does Unity have some sort of super sneaky tag that names exposed to editor array elements along an enum?
so let's say I have an enum that goes like {Red, Green, Blue} and then create a serialized Color[] array, and I want the element 0 to automatically be called "Red" instead of "Element 0"

#

is there a smart and lazy way for that or do I need to create a struct

#

well, found a community-made solution for that

vestal arch
covert dust
#

more long time effort for the same effect 🤷

#

I'm trying to lazy-max the case

#

two clicks instead of one you get me

vestal arch
#

well serialized dict would give more flexibility as to which members to include

covert dust
#

that is not needed

vestal arch
#

but if that's not applicable to your situation then 👍

covert dust
#

what I'm making is a way to serialize game's global color palette

#

all colors will always be mandatory

vestal arch
#

should it even be an enum+array then?

#

why not a struct

#

that way you require the ones at the end as well

covert dust
#

the enum is there for naming which general concept this color represents

#

a struct was my first idea, but that's again two clicks per element

vestal arch
#

you can do that with a struct too, with the member names

vestal arch
#

oh you're thinking of an array of structs?

covert dust
#

ah, you mean a struct like that

#

yeah we just missed each other for a moment 😆

#

I now get it

#

might think about that

vestal arch
#
[Serializable]
struct Palette {
  public Color32 red, green, blue;
}
covert dust
vestal arch
#

an array would be 2 clicks per element

covert dust
#

this is probably a little better

vestal arch
#

1 to add an element, 1 to set the value

covert dust
#

well damn, you out-lazied my idea, well done

vestal vector
neon pivot
#

I've got a question about scriptable objects, how can I use an enum inside of a scpriptable object

craggy veldt
vestal arch
craggy veldt
#

just to show?

vestal arch
#

they're applying bindings/entries/values corresponding to each member

craggy veldt
#

oh no idea then

soft shard
neon pivot
# soft shard You should be able to make a public variable for it the same way as any class, a...

Enums just don't appear in the inspector, and neither unity or visual studio give an error
`using System.Collections.Specialized;
using UnityEngine;

[CreateAssetMenu(menuName = "PhantomDev/New Attack")]
public class Attack_SO : ScriptableObject
{
[Header("Attack Descriptors")]
public string attackName = "{Name goes here}";
[TextArea]
public string description = "This {enter type here} {was/is/could be/may be/etc} {backstory} \n {does this and that}";

[Header("Attack Stats")]
public int damage = 7;
public enum attackType { Sword, Bludgeon, Magic }
public enum attackElement { none, Water, Fire, Earth, Wind, PureMagic }
public bool bleed = false;
public int amountOfUses = -1;

}`

leaden ice
#

There's no difference between an enum and any other type. The type definition is different from a variable of that type

#
// Defining the enum type
public enum MyEnum { A, B, C }

// Making a variable 
public MyEnum myVariable;```
swift falcon
#

currently getting an error that my class doesnt implement inherited abstract members, when it very clearly does

exotic crypt
#

any chance at seeing the base class too?~

swift falcon
#

ye one sec

somber nacelle
#

also !code

tawny elkBOT
still lagoon
#

how do listeners for events "know" when the event is fired? do they check every frame? does the event itself go looking for listeners?

somber nacelle
#

like c# events or UnityEvents?

swift falcon
#
using UnityEngine;
using System.Collections;

public abstract class ItemClass : ScriptableObject
{
    [Header("Item")] //data shared across every item
    public string itemName;
    public Sprite itemIcon;

    public abstract ItemClass GetItem();
    public abstract WearableClass GetWearable();
    public abstract ToolClass GetTool();
    public abstract MaterialClass GetMaterial();
}
still lagoon
swift falcon
#

thats the itemClass script

somber nacelle
#

UnityEvents are a bit different because of how they are serialized, but it's still just a wrapper for a delegate

exotic crypt
#

i have just bar for bar copied and pasted the two classes and its working fine for me. Try removing the methods and use the IDEs "Implement abstracted method" tool tip?

night harness
#

(The mystery behind events is that functions themselves can actually be handled as a stored data type, so events basically have a list of functions they fire off that you add and remove from)

still lagoon
night harness
#

You can call stuff on disabled objects

somber nacelle
still lagoon
#

with OnEnable/OnDisable

night harness
#

People assuming disabled objects can’t use functions is usually a misunderstanding due to them not longer receiving update calls

steady bobcat
#

a c# event such as event Action blah; can be subbed to or unsubbed at any time and invoked at any time.

still lagoon
#

because you can disable an object and change its transform and reenable it

#

etc

somber nacelle
# still lagoon sorry i meant unsubscribe specifically

well c# doesn't have the concept of enabled or destroyed, those are both unity-specific concepts that don't really mean much for the code you write except for some specific methods and properties you might access/use.
if you don't unsubscribe an event then that method will still be invoked because the delegate still has a reference to it. this can lead to memory not being correctly released (the object cannot be GCd if something that isn't also being GCd still references it), and it can also lead to exceptions (like MissingReferenceExceptions which happen when you try to use a destroyed object)

still lagoon
#

learning programming with unity makes it all kinda jumble up together

night harness
#

(Aka: people do that because they should, not because it’s a built in requirement of events)

rigid island
#

when you don't use Unity MB methods, you can use methods to cleanup, such as implementing the IDisposable and call it on the Dispose method

night harness
#

There’s a lot of programming stuff that becomes a lot easier to understand when you figure out what people have to do and what people should be doing

somber nacelle
still lagoon
#

so if C# doesnt have "destroy" or "disable", how do you handle unsubscribing outside of unity? would you do that before setting the object to null?

night harness
#

C# has destroying objects as a feature but Unity’s destroy does a lot more for a bunch of various reasons

night harness
#

usually yeah whatever would set it to “null” would also contain stuff to correctly handle its destruction which might include unsubscribing from stuff

rigid island
#

.net framework /c# does have such

steady bobcat
#

as it says its more for manual release of unmanaged stuff

rigid island
#

I always used that on blazor when component gets disposed

steady bobcat
#

i think using Dispose() to then unsub is misleading

night harness
#

Also it’s not fully an event but you can kinda use the Update() example of how events kinda work in practice, where unity just does an Update() every interval and alive, enabled objects listen to that and receive that call until they don’t need to. Unity doesn’t need to know what is listening to the event it just gives it out to anyone interested in listening

steady bobcat
#

up to whatever you are doing to decide when you want to unsub from events

still lagoon
#

i heard from one of my colleagues that there is some overhead to having an event subscribed

rigid island
# steady bobcat up to whatever you are doing to decide when you want to unsub from events

is this false then

Yes, go for it. Although some people think IDisposable is implemented only for unmanaged resources, this is not the case - unmanaged resources just happens to be the biggest win, and most obvious reason to implement it. I think its acquired this idea because people couldn't think of any other reason to use it. Its not like a finaliser which is a performance problem and not easy for the GC to handle well.
https://stackoverflow.com/questions/452281/using-idisposable-to-unsubscribe-events

still lagoon
#

no clue if there is any truth to that though

steady bobcat
rigid island
#

as long as its cleaned up ye?

steady bobcat
#

👍

rigid island
#

I was always under the impression it was good practice

somber nacelle
hexed pecan
#

You can also have a boolean flag that indicates if it's cleaned up, and throw an error/warning in the destructor if it wasn't properly cleaned up

still lagoon
#

ah i see

#

okay that makes sense, thank you for the explanation

somber nacelle
#

it creates garbage when you sub/unsub. but unless you're doing an absolute fuckload of subscribing and unsubscribing from delegates it won't really make much difference in the long run

steady bobcat
#

I do wonder what the overhead is of unity "messages" as its doing a native -> managed call (somewhat removed in il2cpp)

vestal vector
young yacht
#

i got a question, if i got an object singleton and i subscribe to an event inside Start() i wont need to disable this event with OnDisable(), right? since the object will never be destroyed and Start() will only subscribe to the event once, avoiding memory leaks

rigid island
#

this way if something goes wrong you can easily know why

vestal vector
somber nacelle
vestal vector
# vestal vector I understand that. but im trying to zero in on the problem. making my own wont h...

so could it be that im using the New input system for nav and look, while this script uses the old system? They said it shouldn't matter. and its not like it doesnt work, it does. but the physics just tweaks out and gets worse over time. makes no sense at all. but I'm literally completly lost here. at this point Im willing to start over to day 1 and learn eveything again. but everything is 9+ years old and teaches you to put everything in the update method. setting you up for failure. so idk what to do anymore. @rigid island

rigid island
#

I use Update for my pickup object scripts all the time

vestal vector
# rigid island I have no idea what the problem is, there is too much to catchup to tbh lol Wha...

im told that you should put as little as possible in update for prefomance sake. i mean if its fine its fine, but not good to just go ahead and do that for everything. like checking inputs for every frame for example. for them. they pick it up. it follows the camera. and it drops when they let go. for me: almost the exact same thing, except it bounces up and down. I put it down again, pick it up again, its bouncing more aggressively. progressively getting worse the more i interact with it. as if values are changing on the fly. despite working perfectly for them. my debugs work exacly as expected too. so the script should be working in order properly.

rigid island
#

also depends on too many factors to determine what is ok in Update or not

#

its more about what computations are happening x how many instances so yeah in some cases but not here

lean sail
vestal vector
#

oh sorry, didnt see you mention the thread

rigid island
#

send it in the thread so we dont flood

swift falcon
lean sail
swift falcon
lean sail
#

They quickly break when you want to extend its functionality. Like in your case if you have something else derived from ItemClass, that isnt WearableClass, itll have to return null for that one method everytime.

#

Same like how you're doing for the other methods in WearableClass, which I now realize you likely have more things deriving from ItemClass

swift falcon
#

👍

glacial gull
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TeaCrate : MonoBehaviour
{
    public LevelManager levelManager;
    private GameObject player;
    private Tasks playerTask;

    private void Start()
    {
        
        while (playerTask == null)
        {
            player = levelManager.instantiatedPlayer;
            playerTask = player.GetComponent<Tasks>();
            Debug.Log(playerTask.ToString());
        }

        Debug.Log(playerTask.ToString());
        
    }
    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.layer == 4)
        {
            Destroy(this.gameObject);
            playerTask.CompleteTaskAction(0);
        }
    }

}

Hello, on the code above, I keep getting NullReferenceError for the playerTasks, but none of the debug statements are working?

neon junco
glacial gull
#

there is a tasks component on the player

neon junco
#

Sometimes it can bug out in runtime. Usually I do that in Awake function so it grabs it before the game starts

#

If u need it during runtime then you need to hardline the reference before its used in code

glacial gull
neon junco
#

But is it a character that spawn in to the level ?

glacial gull
hexed pecan
#

An if statement would be more appropriate, not while

neon junco
#

Right so as i gathered with your script you instantiate the character then when it starts your saying while playerTask is null you have to grab its own reference and get its own component ?

glacial gull
#

i added the while loop to debug, but somehow the debug statements are not printing

somber nacelle
#

are you certain there are no other errors before that one?

neon junco
# glacial gull yes

Have you tried just serializefield the Tasks and in the prefab or wherever you have your character and dragging it on so its hard coded ? then getting your own reference you don't really need to if the script is on the player. If your trying to say player equals the instantiated player its going to be like who ?.

glacial gull
#

this is my current log, the watershader errors doesnt seem to affect anything

steady bobcat
#

Level manager is null!

#

I mean player bleh

#

Just read the errors...

glacial gull
neon junco
#

Does it need to be elsewhere ?

glacial gull
somber nacelle
#

read your previous error. that is what has caused your issue.

glacial gull
#

im not sure why though

steady bobcat
#

it is literally as it says 😐

neon junco
#

It cant find the player

somber nacelle
glacial gull
somber nacelle
#

you know how to read, right?

glacial gull
#

Yes

somber nacelle
#

then read the third log in your console in the screenshot you posted.

glacial gull
#

Wait oooooohhh, sorry everyone

steady bobcat
#

yay

glacial gull
#

I have instantiatedPlayer = Instantiate(player); though...

steady bobcat
#

clearly its not happening soon enough

neon junco
somber nacelle
hexed pecan
#

"The object you are trying to instantiate is null" or whatever

glacial gull
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class LevelManager : MonoBehaviour
{
    public GameObject player;
    public static LevelManager Instance;  
    public GameObject instantiatedPlayer;

    private Tasks playerTask;
    // Start is called before the first frame update

    private void Awake()
    {
        Instance = this; 
    }

    void Start()
    {
        playerTask = player.GetComponent<Tasks>();
        SetObjective();
    }

    void SetObjective()
    {
        instantiatedPlayer = Instantiate(player);
        Scene scene = SceneManager.GetActiveScene();

        switch (scene.name)
        {
            case "Intro":
                break;

            case "Boston Tea Party":
                Debug.Log("Current level is boston tea party");
                playerTask.AddTask("Lance des boites dans la mer", 3);
                break;
        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
neon junco
somber nacelle
steady bobcat
#

plz dont confuse them (batty251)

neon junco
#

So don't help ? okay. I remeber why I don't post here..

somber nacelle
somber nacelle
steady bobcat
glacial gull
somber nacelle
#

that is an option, yes. the easier option for you would be to simply merge the Start method of LevelManager into Awake.

neon junco
steady bobcat
#

We understand the issue but its most helpful when we describe as clearly as we can what the problem is. nothing to worry about anymore though

glacial gull
#

I see, ill try it

neon junco
steady bobcat
#

what i say doesnt have to stop you im just a rando user

#

you do you, we are here by choice to help when we want

glacial gull
#

Thank you everyone, i figured it out, it works now!

fast linden
#

Hey guys, I’m having an issue with a dictionary in Unity. I’m storing keys and values, and when I print all the elements in the dictionary, everything looks correct—all the keys and values are there. However, when I try to search for a specific key, it doesn’t find the last key in the dictionary.

For example:

If I add a new key, the previous key that wasn’t being found suddenly works, but now the new key I just added isn’t found.

If I add an empty element at the end, it works, but I don’t want to use this as a solution because it feels like a workaround.

Something seems wrong, and I’m not sure what’s causing this behavior. Any ideas?

lean sail
tawny elkBOT
lean sail
#

also "add an empty element at the end", dictionaries dont have an end, they aren't ordered

fast linden
steady bobcat
#

so you know, a real csv parser needs to handle " correctly but its your data i presume so okay for now

lean sail
#

also i cant tell if theres a difference, since idk the language, but those first 2 columns in your file looks like the same character

fast linden
lean sail
#

then you havent added that key into the dictionary simply

fast linden
cosmic rain
lean sail
#

this would really be solved if you just used an existing csv parser which handles everything properly. you do have debugs in your method though seemingly printing out everything, cant you see in the console if everything appears?

fast linden
#

I am curious why in the printer I see the value but when I search about the key it's give me not founding

lean sail
#

Try printing out all the values at the end of the parse csv method

#

you can go through it with a foreach, then access the key and value

cosmic rain
# fast linden yes

Then add a breakpoint with a condition to break on the last element and step through the code to see if the key-value is added to the dictionary

fast linden
#

thank you @lean sail and @steady bobcat

steady bobcat
#

yes use a debugger to verify each item is added correctly

tame spruce
#

Unity UI: Why does viewport.rect.width change so drastically between resolutions?

chrome orchid
#

hellow, im new in here

#

i made a game its a simple proyect, and i made a build of the proyect but when i run the .exe file, its start with the unity logo and then it stays loading in a grey screen

modern atlas
cosmic rain
chrome orchid
#

hi

#

sorry i didnt see the message

#

this is the game

chrome orchid
cosmic rain
# chrome orchid

I don't see any loading screen. What's point of the video if it doesn't show the issue?😅

chrome orchid
#

thats the build

upper haven
#

Guys so i want to learn more about Unity's C# and i really dont want to waste 5h doing tutorials and in the end have no idea about making stuff on my own

night harness
#

i would suggest wasting the 5 hours

#

as a start

lean sail
#

and you'll waste way more than 5 hours

chrome orchid
upper haven
cosmic rain
#

I don't see any loading screen. Just an empty screen.

upper haven
soft shard
# upper haven Guys so i want to learn more about Unity's C# and i really dont want to waste 5h...

I would suggest starting with w3schools C# course, get some practice on that site with the various topics of the language, then maybe move into Unity tutorials but try to avoid the "how to make x" type of tutorials, as they often skip a lot of important steps for beginners - a lot of "having an idea of what your doing" will come from... Actually doing, making many projects, trying things out, and practicing critical thinking skills as a programmer, and a lot of "avoiding hours on tutorials" as a means of progress is understanding how to break down your own problems into something you can code with what you understand about the language and engine and using resources like the docs, stack overflow, etc - its take a long time, but so will making any kind of game, especially if you plan to release that game one day

upper haven
chrome orchid
#

ill show you a ss

soft shard
chrome orchid
#

@cosmic rain

cosmic rain
upper haven
#

much love to you

soft shard
worldly hull
#

which one is more expensive?

texture cast into texture2d
texture2d cast into texture
sprite.create using texture

cosmic rain
#

Sprite creation probably.

worldly hull
#

btw this is a quite frequent execution

cosmic rain
#

Casts are relatively lightweight

worldly hull
#

the thing is, we have two sets of textures before , because we have a set of poker cards needed to display in 2D and 3D, so we have a set of texture and texture2D

and someone decided to take one set away, we then take away the texture2D , only leaving texture

#

because we wanna reduce the app size

#

the problem is, if i only have texture, i will need texture2D for sprites

hexed pecan
#

What is the actual type of the object that you are referencing with the Texture type?

#

Because Texture2D inherits from Texture

#

Can't you just use Texture2D type reference instead of Texture?

worldly hull
#

mainly two kinds

  1. texture = texture (this is fine)
  2. image.sprite = texture (this has problem)
worldly hull
#

im fine to have t2D or texture

#

but there can only be one

hexed pecan
#

Yes, Texture2D is used for 3D

worldly hull
#

nice ty

night harness
#

texture2d is ideally used for 3d objects

hexed pecan
#

There are also 3D textures, that's why it's called Texture2D

night harness
#

very rare you need just texture

worldly hull
#

i never cross used them before

#

like using t2D on 3D objects lol

night harness
#

yeah as Osmal said, Texture2D is called that because it's a 2D Texture, not because it's meant for 2D stuff

#

i understand the confusion when unity has function names and components ending with 2D though

worldly hull
#

yeah they were so consistent on components when its for 2D projects lol

#

u know, collider2D/collider

night harness
#

yee

worldly hull
#

ok, for 3D poker cards, we gonna use texture2D as it is
for 2D poker cards, we will remove all image components and use rawimage, something like this

#
      RawImage img = null;
      img.texture = GameManager.Instance.cardTexs.GetCard("S0");```
#

where getcard will return a texture2D

cosmic rain
worldly hull
#

yeah the project is quite messy

#

we will interact with material in runtime and change the properties inside

#

this is how we deal with 3D objects

cosmic rain
hushed laurel
#

In my Gadget class, which extends the Item class, of which a List is stored in the Inventory singleton, I have an enum for its type as well as a public field of that same enum. Is there a better way to disambiguate their identifiers other than "Type" and "GadgetType?"

public class Gadget : Item
{
    public enum Type { TurretDrone, StimDrone, ForceField };
    public enum State { Waiting, Charging, Ready, Active };
    public string GadgetName;
    public Color GadgetNameColor;
    public Type GadgetType;
    private State _gadgetState;
    ...
}

Is this even a problem?

leaden ice
hushed laurel
latent latch
#

Why don't you just pass the Type is then in the constructor?

#

Enums are nice because they can cut down the amount of types your project needs

#

For example you may have a single Gadget type with multiple different variations where these enums define each one of them, or if say you wanted to create a type of Gadget1, Gadget2, ect. then you would instead have more types than enums

hushed laurel
latent latch
#

Sorry glanced over it on my phone. Thought you were storing these objects as Type, but seems you named your enum Type instead.

#

Not entirely sure of the question therefore. Is this just a naming convention issue?

latent latch
#
public enum GadgetType{ TurretDrone, StimDrone, ForceField };
public class Gadget : Item
{
    public GadgetType GadgetType;
}```
#

this is what I'd do

hushed laurel
#

I didn't know you could create an enum outside of a class

#

Thanks

latent latch
#

It lives in the namespace (or global otherwise)

hard estuary
# hushed laurel In my Gadget class, which extends the Item class, of which a List is stored in t...

If you want better scalability, use ScriptableObjects in this role. That way you can create dozens of new types without opening code editor. You will also be able to create some type-specific code for each ScriptableObject's script.
Enums on the other hand are great for fixed number of types. It's also easy to find all references of particular type. The downside is, that there is no separate script for each enum, meaning that developer who wants type-specific code will have to insert it into some script, potentially making a long script file.

somber kite
#

There might be a bug from version 6000.0.30f1+. I have a container VisualElement in which I add toggle elements and I "refresh" when I click a button. The first time when it initializes it's fine, the values change when the toggles are clicked, the second time and onwards breaks them - it makes them unable to change their value when they are clicked.

I do clear the parent element every time I "refresh" and I also create new Toggles based on dynamic values and add them to it. I also register a callback for value changed on each (new) toggle which after the second time it "refreshes" never gets called, but the ClickedEvent Callback does get called on them.

The same logic works with no issues in version 6000.0.11f1

trim schooner
#

This is a code channel (the name gives it away!). Unless your question is code related (it doesn't look liek it), delete it and ask in #🏃┃animation ... if it is code related, show the code

dense pasture
swift falcon
#

how would i go about fireing a raycast in the direction of my mouse compered to the player and getting the postion of the first object it comes into contact with

#

and is there a way of detecting what object the raycast hit

leaden ice
#

and use that in the Raycast

leaden ice
swift falcon
#

perfect thanks

glacial gull
#

Hello guys, so I have a game with multiple scenes. However, when i change to another scene, it takes way too long to load. Is there a way to accelerate it?

leaden ice
#

also use the profiler to see if there's any code of yours happening during scene activation to slow things down

glacial gull
#

Is there a way to load it before so the switching is faster?

cosmic rain
#

You could do async scene loading.

leaden ice
leaden ice
#

Look up:

  • Unity additive scene loading
  • Unity asynchronous scene loading
  • Unity AsyncOperation.allowSceneActivation
glacial gull
#

Thank you!

karmic stone
#

today i learned that csharp doesnt have a modulo operator, it only has a remainder operator. so much pain and suffering.

flint dagger
#

For something like the player is it ideal to have a bunch of smaller classes attached and then like one "master" class that they all have references to that they use to interact with each other? Since I was told it's best to have the functions split across several classes.

leaden ice
flint dagger
#

So the master class can have information like "am I dead" and if like the bullet raycasting in the weapon script and the FOV for sprinting in the movement script both need the main camera than the master can hold the main camera object reference.

leaden ice
cosmic rain
leaden ice
#

it behaves differently with negatives

karmic stone
#

modulo returns postive number within range in most languages. which is what you need with circular arrays.

#

it doesnt return a negative. for csharp, programmers wanted efficienty, so they dealt with this quirk as most of the time they only dealt in positive numbers (read from a stack overflow source, could be wrong)

leaden ice
cosmic rain
#

So the difference is that it doesn't preserve the sign(in C#)?

leaden ice
#

StackOverflow has many examples

karmic stone
flint dagger
karmic stone
cosmic rain
karmic stone
#

cant have negative indexs in a circular array tho, thats the problem

cosmic rain
#

Just abs it then

flint dagger
karmic stone
#

yeah, i already solved it, its just a problem because how i implemented it, it caused me much pain till i figured it out.

leaden ice
#

it's not just a sign issue

karmic stone
#

its also a distance issue

#

abs(-1) gives you 1, but it should be maxitems - 1

leaden ice
#

yeah your explanation is pretty unclear. Sounds like you probably just want to project the desired movement direction on the plane of the wall

#

You can use Vector3.ProjectOnPlane for that

lucid brook
#

I'll just delete it for now and try to come up with a better way of explaining it lol. I did think about using ProjectOnPlane but I don't think that would work.

leaden ice
#

Why not?

karmic stone
leaden ice
#

You can only make custom operators with your own user-defined types

karmic stone
karmic stone
#

that sucks :/ all good, ill just make a user defined operator then

leaden ice
#

you can't define any custom operators between int and int

#

You can only overload operators for your own custom types

karmic stone
#

oh that, just sucks hardcore. so i need a wrapper for int so i can define custom operators

leaden ice
#

Sure but it seems like a simple function would be simpler, no?

#

you could make an extension function too

lean sail
#

If you made a wrapper, you'd also need more functions to get it working in place of an int. Just use an extension method

karmic stone
#

i want originally to just replace the % operator so i dont have to worry about edge cases during my coding when dealing with mod, i can replace a % b with mod(a, b), just seems more simplistic if your able to replace the operator. i just wanted a way to keep the same style of using arithmatic operators to do simple arithmatic, but it just seems like the ways to do this wouldnt be better over a function.

#

thank you for all the help though, yeah going to just define a static mod function with 2 ints, better for my style.

next sparrow
#

Hello, I'm having a hard time understanding the difference between IEquatable and Linq Single. I have a structure and an array of this structure. I need to find and return the struct inside the array based on a single property. With Linq Single, I can do this
mystruct.Single(e => return e.property == value);

#

The issue is that each time I need to look into the array, I need to call this. I'm always checking for the same proerty, kinda like a dictionary with its key. (But I don't want a dictionary cause I want to be able to set up the array in the inspector)

somber nacelle
#

I don't want a dictionary cause I want to be able to set up the array in the inspector
just FYI, there are assets that allow serializable dictionaries so you can use a dictionary that can be modified in the inspector

next sparrow
#

I thought I could make the comparison direct with IEquatable but it seems even if I implement the Equals and == methods, I would still need to loop on the array itself

next sparrow
#

To reduce the amount of third party stuff in the project

rustic cradle
#

hi, can anyone help me with unity ml-agents, im trying to train a drone using rl

somber nacelle
#

no matter what getting a specific object from an array without just using the index is going to require looping over the array

rustic cradle
dense tinsel
#

when making a progression based scene, like stuff appear after certain achievement, is there better way than setup the whole scene again when load back to it

next sparrow
#

I like the linq solution but I just want to avoid repeating the same code again when looking in the array. Can the lambda function be replaced by a normal one?
slots.Single(e => e.display == display)

#

Something like slots.Single(FindDisplay(e, display)) ?

somber nacelle
#

that would require a lambda expression if you are passing in a different display each time you call the method. if not, then display can be a field and your FindDisplay method just needs to take whatever type e is as a parameter and as long as it returns a bool it would just be slots.Single(FindDisplay)

next sparrow
#

Got it. Thanks!

sudden ruin
#

how do i reference a scriptobject or a prefab in a json file

lean sail
sudden ruin
#

like add a id field in the scriptablaObejct script?

lean sail
sudden ruin
#

where is this dictionary be? is it make a manager script, slap it on a gameobject, drag all the SO into it ?

sudden ruin
#

ok i jsut wanted to know how people does it

cosmic rain
sudden ruin
#

for my context is save/load the previous played character

fleet gorge
#

I'd like to implement Firebase into my game, and can't decide between just using the REST API and downloading the full SDK

#

I'm not exactly sure if it's a must to download the SDK or if I can get away with just using the API. Currently I only need authentication and database

lucid zealot
#

Hello, I've got an issue with my UI element. I create a card prefab and I add it to a game object who as a content fitter on it and the prefab scale down automaticaly. I tried to remove or change the Content Fitter but that doesn't work eighter.

Here is a quick demonstration of the issue.

#

P.S: The card bellow is the goal to achieve (I keep it to know the correct scale after I fix this issue)

tough carbon
#

I have issue with object finding.
There are lots of objects of different types. Nps can be looking for object of particular type. How to implement pathfinding of nearest object without brute force all objects of this type? It could be too ineffective

plucky inlet
marble sleet
tough carbon
tough carbon
tough carbon
night harness
#

how many is a lot

marble sleet
#

how about quadtree or oct?

tough carbon
night harness
#

100-1000 viable objects?

#

eg. when you say npcs are looking for a specific type of object, is that 100-1000 before or after it found those objects of said specific type

tough carbon
plucky inlet
#

How often do they check for those objects? Are they changing over the lifetime, so objecst can move, or npcs can move dynamically?

tough carbon
plucky inlet
#

Do you need all updates at all times?

tough carbon
plucky inlet
#

Just sounds like you are trying to cover everything all at once without asking, what you need at what specific point

lean sail
cosmic rain
tough carbon
fleet gorge
#

and it greatly inflates my app size

#

i kinda want to use the API instead of downloading the SDK

tough carbon
inner needle
#

Hey guys I think I'm poorly designing my animator, it's leading to some animation delay issues. I have 2 states, a "target locked" state and "free look state", the LockedOnHub is handling the animations in the target locked state. But when I run the animation, the Hub is causing animation delay because it doesnt move straight to the next animatio, rather it goes "StrafeLeft" -> Hub -> "StrafeRight".

plucky inlet
inner needle
tough carbon
cosmic rain
tough carbon
cosmic rain
#

At that point you're gonna have more important problems than trigger messages.

lean sail
fleet gorge
#

yea im really just seeking public opinion rn

#

one of the challenges im facing is encrypting my key

night harness
tough carbon
night harness
#

this problem has no solution

#

only better

plucky inlet
# tough carbon I am sorry, I don't realize what you mean. Why do I want know that throwing tock...

you are trying to make a system, that just handles everything at all times and hope for some magical system to catch up with that idea 😉 You should think about your core system in general, what updates do you need from the npcs. Does your player always see every update? Can they pause while being offscreen and so on. There is a lot more thinking to it before even touching any code to get a good structure in something that sounds like a live sim for npcs

marble sleet
tough carbon
night harness
#

theres probably a hundred

#

with a lot of different pros, cons, time and skill requirements

marble sleet
#

but you need to rebuild the tree to handle those objects to match the quadtree

tough carbon
cosmic rain
tough carbon
#

I want to make tags like liquid, fire, weapon, e.t.c. Each object has at least one tag. Now I don't know, should I add tags to the terrain (floor, walls).
NPS can interact with objects. Game os around manipulating NPS's, so their ai works beyond player vision.
When nps decides, what they wanna do, they compare distance to the objects with needed tags.
How could I make effective finding any object with needed tag?
P.S.
Nps could want object with two or more tags at the same time

night harness
#

i don't say this to be rude but to give some perspective, some people's whole full time job is doing what you are trying to do here

#

there isn't one single answer people can just point you towards, it really depends on how big your game is and how much you need to "solve" this

tough carbon
tough carbon
woeful hamlet
#

How do I get references to objects I set in the editor to stick around/be properly recreated when I reload scenes?
I've got a singleton scoreManager to track my scores and update a text field to display the score, but as soon as I reload the level, the scoreManager loses the reference to the text field.
I get why, because the original text field object is gone, but how do I get the scoreManager to set a reference to the new one when I reload the scene?

#

When I reload the scene (to reset the level and increase the difficulty), the Score Text reference becomes None.

quartz folio
#

Keep it in the same scene/don't destroy state, or use a singleton in the same scene that's overridden by new instances on scene load

hard estuary
# woeful hamlet How do I get references to objects I set in the editor to stick around/be proper...

When I want something to persist between scene reloading, then I usually put it in a separate scene. Unity support additive scene loading, meaning you can have multiple separate scenes at once, and one of them can be used for persistent GameObjects. Alternatively you can use DontDestroyOnLoad to automatically move it to such scene (but try not to accidentally make duplicates).
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/SceneManagement.LoadSceneMode.Additive.html
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Object.DontDestroyOnLoad.html

woeful hamlet
inland garden
plucky inlet
#

You have to make sure, the port is available and also the correct ip is being targeted, which is not localhost

inland garden
plucky inlet
inland garden
#

I added 7777 port inbound on Windows Defender Firewall, do you mean this?

plucky inlet
#

your VPS needs to open that port too, not just your windows system. or is your vps hosted on your machine?

placid edge
#

I've been looking online for tutorials on how to make objects not exit another object, using things like edge collider and such, however the object in question I want to contain objects in is a 2D circle, if I were to use edgecollider2D, would i run the risk of having thousands of edge colliders and if so would that be a problem, or does unity handle circles with edge colliders well?

#

i figured it out, it doesnt freak out 👍

cosmic rain
#

The only ways you can optimize it is by:

  • reducing the amount of iterations(limit the area in which items would be considered at all)
  • spread it over time
  • spread it over threads
tough carbon
unkempt meadow
#

Guys, setting a bool to true makes unity not be able to enter playmode. I even made sure there is no infinite loop. What is going on here?

cosmic rain
cosmic rain
tough carbon
cosmic rain
#

Well, maybe not the smallest, but you're gonna have many other problems too. If you're going for complex ai with more than 10 agents active simultaneously, you should probably look and dots/ecs.

cosmic rain
tough carbon
cosmic rain
ruby creek
#

Hey Folks,
Have a general question about ECS. Let's say I have a camera, and input controls camera, it don't interact with ECS data in any way - at least for know, It's okay to put Camera controls just as Script onto game object, or should I aim to implement all of it as part of ECS anyway?

unkempt meadow
#

!code

tawny elkBOT
unkempt meadow
#
 IEnumerator RotateRandomly()
    {
        finished = false;

        Vector3 randomAxis = new Vector3(Random.Range(-3, 3), Random.Range(-3, 3), Random.Range(-3, 3)).normalized;
        float randomAngle = Random.Range(-rotationAngle, rotationAngle);

        randomRotation = Quaternion.AngleAxis(randomAngle, randomAxis);
        rotationSpeed = Random.Range(0.02f, 0.04f);

        while (Quaternion.Angle(transform.rotation, randomRotation) > 0.1f)

        {
            transform.localRotation = Quaternion.Slerp(transform.localRotation, randomRotation, rotationSpeed);
            yield return null;
        }
        finished = true;
    }

This never returns true. How come? I tried increasing the error threshold

hexed pecan
unkempt meadow
#

ooooh

#

there you go

#

I like it when it's simple

radiant marten
#

I am going to be doing something in my game where there will be multiple computers in the world. And each computer will have its own "file system." This file system will be interactable on some computers(like the users), with the ability to save things like notes to text files, doodles/images to some image format etc. So assuming I have these computer gameobjects in the world, what's the best way to have these virtual file systems that I can attach to them? I'm thinking ScriptableObjects? But I'm uncertain amount the idea of modifying them. I already have a basic file system structure that I load/save to json. But I want to be able to set up and organize the file systems for each computer separately, so I imagine I need some sort of asset to link the configuration to

placid edge
#

is alright i figured it out, its just cuz of their shape

latent latch
steady bobcat
#

if you want some shared configuration that each instance shares that you dont expect to save during runtime, a SO is a good fit.

radiant marten
#

🤔 alright so either way file system will need to be saved separately

#

thanks!

steady bobcat
#

well they can be separate files or many instances can be in 1 file.
json isnt efficient for lots of data btw so consider alternatives if these can get big

radiant marten
#

unless that will also be an issue

#

though the folder structure will not really be that large. Probably some standard folders like a documents folder, pictures folder and such with a few files per computer. It won't have an entire actual operating system amount of detail

steady bobcat
#

hard for me to say, it could be just fine for you or become an issue later when things get very complex
probably fine to leave as json then!

#

If you are interested though, other solutions such as protobuf and bebop exist.

#

these are binary serializers (better than the c# binary class serializer)

radiant marten
#

yeah I was gonna say I heard the C# binary serializer is not very good. I'll check those out, thanks!

steady bobcat
#

np. where I work we use protobuf for remote update-able config + network communication (if applicable for the game).
for config we edit/store in json but load and save as proto binary to then be used at runtime.

#

amazing size savings! (e.g. 20KB -> 3KB)

chilly surge
#

If you are transferring JSON over network though, with compression the space saving of another serialization format is basically negligible. JSON is very compressible.

steady bobcat
#

if you compress anything it will be better but it wont beat a purpose build serialization format

#

protobuf is good because data is identified by an int id and is specifically serialized/deserialized with generated code

chilly surge
#

It won't beat it, but the difference between JSON + compression vs protobuf + compression is a lot smaller, to the point where it's unnecessary in a lot of cases especially at the cost of having to bring in an entire library.

#

It's a different story if you are doing something like storing on disk because then you would need to write additional de/compression code, but for network transfer the compression is practically free in terms of implementation cost as every web server supports it.

steady bobcat
#

yea i dont expect the compressed result to differ by much as both contain some same data. We use protobuf as it makes for an efficient cross platform binary serialization system (we have some servers written in scala). Was already a thing when I joined.

#

the messages are defined once and shared, once code is generated its already usable and reliable.

chilly surge
#

Yeah that advantage of protobuf definitely still exists, it's just the space saving aspect that's not really a factor.

steady bobcat
#

If the application is fast high rate data transfer then its great as we can skip compression and worry less about size.
Im used to it so I like it 😄

chilly surge
#

Right, real-time data is an entirely different field as well.

ionic grove
#

Hey guys - I'm trying to copy over the transforms of a player to a ragdoll, and it's still T-Posing when I spawn the ragdoll in. I'm using this code to make it happen. Is there anything you can see as to why it wouldn't be working? I have confirmed that it is an identical hierarchy and the parts are lining up like we'd expect.

private void CopyBonePositions(Transform source, Transform target)
{
    target.SetPositionAndRotation(source.position, source.rotation);

    // Iterate through all source children and match them in target
    foreach (Transform sourceChild in source)
    {
        Transform targetChild = FindChildInHierarchy(target, sourceChild.name);
        if (targetChild != null)
        {
            CopyBonePositions(sourceChild, targetChild);
        }
    }
}
leaden ice
#

maybe targetChild is coming back null for example

#

you can't know until you debug

ionic grove
#

Lol yeah I've tried debugging and didn't see anything, which is why I came here to see if anyone saw something obvious that I didn't see

leaden ice
ionic grove
#

There are no nulls

leaden ice
#

what debugging steps did you take, and what were the results?

ionic grove
ionic grove
leaden ice
#

do you have an Animator?

ionic grove
#

I have an animator on the source object, but not the ragdoll

#

The order of operations is that I spawn the ragdoll in, then copy the values over

leaden ice
#

maybe you're copying from the prefab instead of the object in the scene for example

lapis zephyr
#

ohhh oops

#

okay my bad

#

ill delete it

atomic whale
#

I've just gotten into building navmeshes at runtime with NavMeshSurface.BuildNavMesh(). I found GetBuildSettings() but there is no SetBuildSettings()? I'd like to restrict which layers the navmesh uses.

zinc flax
#

Hello, I have an issue with my 2D game. I created a camera that follow the player with an effect that apply bounds clamping after smoothing. So it kind of follow the player without being locked to the player.

The problem is when I move, the camera is following the player but it's not smooth at all. It's like the fps is very low while it is not. There is no problem if the camera is directly locked to the player but with my technique, it's flickening.

Can anyone revise my code and tell me the issue?

https://pastebin.com/jCpk0eCJ

somber nacelle
#

obligatory: use cinemachine

zinc flax
somber nacelle
#

that depends, are you currently struggling with camera code that could easily be replaced with a simple cinemachine camera?

zinc flax
#

I don't know what a cinemachine camera is. I'll look up on the internet.

somber nacelle
atomic whale
neat torrent
#

whenever i tab out of my unity game the frams drops to 10fps? i have run in background checked on as well does anyone know how to fix this?

naive swallow
#

Most computers throttle resources to programs that aren't focused

somber nacelle
orchid nymph
#

dang- sorry

zinc flax
#

Is there any tools I can use for generating 2D chunks easily?

hexed pecan
#

2D chunks is not very specific

zinc flax
#

I am generating a world like the mini game Motherload. I need to generate the world in chunks around the player to avoid overloading.

cosmic rain
zinc flax
#

I did create a chunks system but I do have some bugs in it so I was wondering if there is a tool that can manage that stuff to make it less complicated.

#

I don't have performance issue but my chunks system is a bit odd..

cosmic rain
#

Maybe something on the asset store, but chunking is not very common in 2d afaik.

#

Maybe try without chunking first? There might not be an issue in the first place.

zinc flax
#

no I need chunks lol.. my world goes as deep as 500,000 tiles.

#

can't load that much in one go

cosmic rain
#

It doesn't matter how deep it goes as long as only the tiles on the screen are rendered. Which should be happening by default.

zinc flax
#

it need to be naturally generated by the game

#

randomly

cosmic rain
#

Can you not generate it once on game start?

zinc flax
#

for that many tiles no

#

how long do you think it take to generate 60 millions tiles with random generation in it?

cosmic rain
#

Depends on how you do it. Can be anywhere between less than a second and a few minutes.

zinc flax
#

wtf

cosmic rain
#

Anyways, if you're set on doing chunking, you should either look for an asset, or try to fix your implementation. If you have a more specific question, feel free to ask.

zinc flax
#

how do you generate that many tiles in a few seconds?

cosmic rain
#

If it's just assigning a value to a tile based on Boise, it could be pretty fast. Don't underestimate computers.
Then there are compute shaders, multithreading, burst compiler that can boost the process x10-x1000 times or even more.

#

It highly depends on your algorithm and requirements for the procedural generation

zinc flax
#

well I do generate caves system with noise that draw black dots on a white png then it apply that to the world generation.

cosmic rain
#

Why does it even need be a PNG in the process. Sounds inefficient.
But anyway, all is assumptions until you test and profile it.

#

I'd say, test the simplest implementation (no chunking) possible and see how fast it goes.

#

Then you have some info to work with

zinc flax
#

for the rest, it's a simple system that create many layers. It start from generating dirt with 100% probability and slowly goes from 0% crustrock to 100% crustrock at a certain depth, then it does the same from crustrock to mantlerock.

Then I am generating ores everywhere on top of every tiles with a probability.

swift falcon
#

Guys why my WASD works like if i was moving character in worldspace or something? (But this only happens when i use Unity Recorder)

#

Very weird

#

I mean the recording package

somber nacelle
#

is this a code question?

zinc flax
cosmic rain
swift falcon
zinc flax
#

is there any way to interupt the loading in process?

swift falcon
#

Well the package is made of code

zinc flax
#

or do I just click X

somber nacelle
zinc flax
#

How do I interupt the Application.EnterPlayMode ? I am stuck loading forever.

somber nacelle
#

gotta kill the process

leaden ice
zinc flax
#

no I don't have infinite loop, I am generating 1 million tiles.

leaden ice
#

well you might have an infinite loop, or just one that takes a really long time

#

If the 1 million tiles are all GameObjects yeah you're going to have a bad time there

zinc flax
#

ok I think you spotted my problem then

somber nacelle
cosmic rain
somber nacelle
zinc flax
#

I'm using this to generate my tiles:

public List<Vector2> worldTiles = new List<Vector2>();
public List<GameObject> worldTileObjects = new List<GameObject>();
public List<RuleTile> worldRuleTileObjects = new List<RuleTile>();
public List<TileClass> worldTileClasses = new List<TileClass>();
#

adding to the list each tile

leaden ice
#

it's just a bunch of field declarations

#

and empty lists

zinc flax
#

no but im adding them to the list when generating them

leaden ice
#

sure, and yeah as mentioned if you're making a million GameObjects you're going to have a bad time

zinc flax
#

Ok I checked further, I do create a new GameObject each tile

cosmic rain
#

I was assuming you're using the tilemap. Using gameObjects is gonna be inefficient even if you're doing chunking.

zinc flax
#

so switching to tilemap and then using compute shaders, multithreading, burst compiler will speed up my generation by 10000000 times lol

cosmic rain
#

Possibly. Maybe even without compute shaders, multithreading and burst.

#

gameObjects might not be the only issue.
You really need to profile to understand the culprits

dim umbra
#

is there any way to layer a camera without pixel perfect and a camera with pixel perfect at the same time? Seems like you can either have everything be pixelated or nothing...

rigid island
dim umbra
#

My main game is not in pixel perfect, but I want to make a background effect using pixel perfect

#

with the rotating sprites thing

rigid island
#

maybe you can toggle them but that sounds like more problems

zinc flax
#

I got a question about tilemap.. is it possible to have a tile that is not defined with rules, just one simple texture? I need to just do a procedural generation of tilemap instead of creating gameobject but it seems that creating tilemaps is only for rule tiles. I try selecting a tile on my terrain generation code from this:

[Header("Foreground Tiles")]
public TileBase dirt;
public TileBase grass;
public TileBase crustrock;
public TileBase mantlerock;
public TileBase mantlerock1;

But I can only select tile that has rules in them.

#

So how to create a tile without rules?

#

So I created a tile like this:

Then I assigned a sprite to it.

But I cannot select the tile I created at all

somber nacelle
#

that's not how you create a tile, that creates a tilemap

#

tiles are assets. they are part of tile palettes.

zinc flax
#

oh ok so I must create a new tile palette inside here?

somber nacelle
zinc flax
#

thanks

zinc flax
wide totem
#

I forgot to take a screen shot, but very often i am getting the 'Value cannot be null. Parameter Name: _unity_self"
I am able to fix it just by restarting unity/relaunching, but is there anything i can do to help prevent getting this error, or something i can keep in mind that might be causing it?

rigid island
#

it could be anything, from a bug to a corrupted asset or something

#

best you do some narrowing with process of elim

wide totem
#

alright, might be difficult because it seems to appear randomly but ill track whenever it appears and what i did previously

rigid island
#

one quick thing you can try is deleting library and refreshing the project, hope it was some lingering bad cache or something

#

also narrow down if its project specific or unity version itself, try blank project etc.
copy project into a new version of unity etc.

wide totem
#

ty for the suggestions, will test them out

zinc flax
rigid island
ember ore
#

I want a customizable character system in my Game. Like the Player can equip Armor, weapons, hat's, Boots and whatever. Should of course be visual too.

Would you choose 3D for this, some 3D Modell that you equip with different meshes Like Armor, weapons e.g. or would you choose 2D instead? But If 2D, how would you make the Sprites modular and animated at the same time? 🤔 Glad for any Help!

vestal arch
ember ore
vestal arch
#

depends on your skillset

ember ore
# vestal arch depends on your skillset

Well for 3d you simply attach meshes in the right Slots and it works instantly. How would you realize an modular 2D character where you can easily Swap items, armors or the Players Race for example?

modern atlas
ember ore
swift aspen
#

The solution you go with here is heavily dependent on your requirements

ember ore
swift aspen
#

Well what sort of animation are you trying to achieve? You can use a bones approoach and animate the bones similar to how you would animate a 3d character

ember ore
swift aspen
#

Doesn't have to be, but there will be limitations to what you can do. For instance if you look at only the helmet in that animation you could say it's only 3 different sprite frames. Assuming you give each helmet you make those frames you could animate both the position and sprite using a bones approach

#

Typically bones moving from one position to another is smoothed to give you nice smooth animation, but you could ignore the smoothing and jump from keyframe to keyframe to give it a snappy animation

vestal arch
deep stirrup
#

CharacterController has a bool called EnableOverlapRecovery. Is there a way to detect, when CharacterController "recovers overlap" to see if player being crushed by a moving wall for example?

plucky inlet
deep stirrup
#

you mean OnControllerColliderHit(ControllerColliderHit hit)?

plucky inlet
#

Or collisionenter and so on, those should work too

deep stirrup
#

I thought of this, but I don't really know how to detect if other collider penetrates the character controller. Maybe some checks if hit.point is within collider and not on it's surface will do the thing, but I didn't figured it out yet

plucky inlet
#

Did you read the docs about that part? ". This only concerns static objects, dynamic objects are ignored by overlap recovery."

deep stirrup
#

yes, I can't really use overlap recovery because of this

#

I mean, maybe there's built-in way to detect colliders penetrations

plucky inlet
#

Penetration is, when you enter a collision.

#

if you want to avoid that, collisionenter is basically your callback to react to.

#

*on dynamic objects

kind willow
#

long story short, how do I divide longs? I am fine losing like 3-5 digits of precision

leaden ice
#

If you don't want integer division, cast them to double first

kind willow
#

would that work just fine with the biggest/smallest longs?

leaden ice
#

In what sense? What do you mean by "work just fine"?

kind willow
#

eh, a silly double checking

#

I am not having a good grasp on those variable types

leaden ice
#

long is the same as int, it just has twice as many digits

kind willow
#

so I was not sure if long is always lesser than max double

leaden ice
#

63 binary digits vs 31 for int

kind willow
#

yet now I have searched again and yeah

#

double like float can be very huge

#

sure bigger than any long

leaden ice
#

yes max long is less than max double but that doesn't mean double is very precise when dealing with extremely large numbers

#

what are you trying to do and why are these questions coming up?

kind willow
#

getting time from a server as long
using that to make daily rewards

#

doing division for a timer

leaden ice
#

where does the division come in

kind willow
#

I don't have to do that for this, yeah

#

I just represented the timer as a value from 0 to 1 and wondering why does it not working

#

then I figured it's long being rounded

leaden ice
#

it's an integral data type like int

kind willow
#

yeah figured somewhere along the way

leaden ice
#

there's also no reason you would be dealing with anything anywhere approaching "the largest long values" when dealing with such a timer

kind willow
#

I mean what if double is small and I can't cast big long into one in the first place

#

cleary not the case but I didn't know

leaden ice
kind willow
#

like what if I have a long of 9999 but double is overflown at 999

leaden ice
kind willow
#

yeah

leaden ice
#

in that case you would only be doing division with relatively small numbers anyway

#

assuming your long represents seconds or ticks, you would do:

long timeThroughDay = currentTime - dayStartTime;
double progressThroughDay = (double)timeThroughDay / timeUnitsPerDay;```
kind willow
#

exactly what I doing

leaden ice
#

then what are you worried about

kind willow
#

fair

leaden ice
kind willow
#

I got used to think of worst cases

#

haven't think that I won't encounter the worst case in this particular division

leaden ice
#

also a word of advice it might be better to write this code using DateTime and TimeSpan than just long

steady bobcat
#

If you can work with time span, otherwise use DateTimeOffset to work with Unis MS

#

I often work with unix ms directly as we prefer to store date+time in this way but be smart and use TimeSpan/DateTime/DateTimeOffset when you can to make life easier 🙂

mellow sigil
# kind willow like what if I have a long of 9999 but double is overflown at 999

Also this isn't a problem even if you had very large numbers, all that would happen is that you'd lose some precision (which you said you're ok with.) Double doesn't "overflow" the same way as integers. If (theoretically) the max integer precision of double was 999 then casting 9999 to double would result in a nearby number like 9996 or 10001 for example.

#

but the real limit for double is 2^53 which is 9,007,199,254,740,992

misty drift
#

Hi! I'm trying to implement "cobo" system - player must enter several keys in order to cast spell. For example on gamepad a-a-x-b => Fireball. (or you may be saw how it's done in Helldivers 1-2 with arrows)
I thought implementing New Input System to handle key clicks, so it's configurable. But now I'm a bit confused how can I create combos via editor.

The idea was to create SO and put list of actions there, but I can't figure out if it's possible, because I can't drag-n-drop actions from Input System config.
Could you please help me figure it out? May be It's incorrect approach and I can do it differently?

leaden ice
misty drift
#

Hmm.. for example I can create Enum for Actions, and then convert it to what I need. This way I can use it in SO. And then in Managers/Services do conversions/combo logic?

leaden ice
#

an enum for your concept of a button or whatever in the game

misty drift
#

Yep, like enum { Abutton, Bbutton, etc..}

leaden ice
#

like cs public enum InputCommand { Up, Forward, Back, Down, HighKick, LowKick, HighPunch, LowPunch }

steady bobcat
leaden ice
#

Like when you see a move list for street fighter - you want those things

steady bobcat
#

ah yea thats a good idea

misty drift
#

Yep, this is what I want to achieve. You gave me good idea where to start, thanks a lot!
I've being thinking for some time and couldn't figure it out, and as always - solution is as simple as it could be 🙂

naive swallow
vestal arch
leaden ice
vestal arch
leaden ice
vestal arch
#

it's not exactly a sign bit

#

it still has a value

leaden ice
#

Two's complement uses the binary digit with the greatest value as the sign to indicate whether the binary number is positive or negative; when the most significant bit is 1 the number is signed as negative and when the most significant bit is 0 the number is signed as positive.

vestal arch
#

a uint32's 31st bit has value 2147483648
a int32's 31st bit in two's complement has value -2147483648

#

unlike sign-magnitude where the sign bit is literally just the sign

#

as far as ive seen, "sign bit" is usually for when the bit is literally just for a sign, like in IEEE 754 floats or sign-magnitude

leaden ice
#

look we both understand how it works. I don't think a pedantic semantic argument here will be productive.

vestal arch
#

sure, but i wouldn't assume the person you're answering to does; imo saying that a 64-bit type has 63 value bits is misleading

#

it still has 2**64 possible values

true heart
#

Has anyone used RealWear with Unity?

steep herald
#

I want to break my work into multiple scenes. I'm trying to achieve a behaviour where awake is called on all active objects across 2+ different scenes before start is called on any object across any of the loaded scenes.

Idea is self init in awake -> reference other classes in start but consistent across 2+ scenes.

I need a clean reset between each transitions. Idea was to use SceneLoadMode.Single on the first of the scenes, and then additive for every subsequent scenes. Set the allowSceneActivation flag to false on the ops handle, and turn them all on when every scene is ready. Problem is progress does not seem to begin on the additive scenes if the one loaded as single hasn't completed. Any idea?

steady bobcat
#

Its easier to init things yourself manually in such a situation imo

leaden ice
steady bobcat
#

smart guy

steep herald
#

Ugh, there's a lot of work done that'll need refactored. Was hoping for a hack. Thanks, I'll go this way then

leaden ice
#

One option is to have all these scripts subscribe to a static event or two in OnEnable and invoke them when you know everything is ready to be initialized.

#

that way you don't need the central manager to have references to everything

steady bobcat
#

Id avoid static in this situation as this should be per scene

somber tapir
#
if (velocity.x > 0 && drag.x > velocity.x)
{
    drag.x = velocity.x;
}
if (velocity.x < 0 && drag.x < velocity.x)
{
    drag.x = velocity.x;
}
if (velocity.y > 0 && drag.y > velocity.y)
{
    drag.y = velocity.y;
}
if (velocity.y < 0 && drag.y < velocity.y)
{
    drag.y = velocity.y;
}
velocity -= drag;

Is there an easier way to do this? Basically, I don't want the drag to be stronger than the velocity .

nimble pulsar
#

So i'm encountering an interesting bug, i've got a chain lightning effect on my game, and when it triggers it does an animation setting the scale of it's collider from 0-15 over 4 seconds (Followed a tutorial) The odd part is it's interacting with my Plot systems, and as they're "firing" it's causing the OnMouseEnter/Exit script to play from my plots... But the mouse is just sitting on the plot.

 {
     sr.color = hoverColor;
 }

 private void OnMouseExit()
 {
     sr.color = startColor;
 }```

I've looked at layers and i think i'm missing something maybe slightly obvious here lol.
#

If there's multiple of them firing, it seems to not even register any mouse at all.

naive swallow
#

If the scale is changing when you hover things, they might be scaling out of hover range, which causes them to scale back to normal, which would cause them to be hovered again, and so on

mellow sigil
#

OnMouse events trigger only on the first collider under the mouse. So if the lightning effect has colliders (it's not clear which collider's scale you're changing) and the effect is on top of the plots then they'll block the OnMouse events

nimble pulsar
nimble pulsar
mellow sigil
#

No, you'll have to do your own raycasting

#

(afaik)

naive swallow
#

Do you ever need the lightning to be interacted with any sort of physics query? You could put it on the IgnoreRaycast layer, pretty sure OnMouseEnter uses a raycast internally

nimble pulsar
naive swallow
#

Might be worth a try?

nimble pulsar
#

yeah im gonna see here

#

Learning more about Raycasting and UI elements this project than i have in the past lol;

nimble pulsar
naive swallow
#

Good to know that it doesn't affect physics events too - I legitimately wasn't sure

nimble pulsar
#

Now a question regarding particle systems, Does anyone have a good video going over them?

I'm trying to make the size of the "crackling lightning" particle there not as lengthy. lol.

nimble pulsar
#

Didn't see that far down!

unreal notch
#

Hey I'm trying to fix an edge case scenario with my movement script that happens when moving up a slope, onto flat ground

my player character gains more y height than is needed to line up with the flat ground, and as a result, ends up briefly being registered as not grounded.

I've been debugging this for a while and narrowed the issue down to that, but I'm not sure how to address it in a way that wont raise other issues (i.e. I can widen the threhhold for how far the ground can be to be considered grounded, but this results in the same problem reoccuring when traveling down a slope from flat ground)

if (hit.distance <= skinWidth + 0.0001f ) collisions.below = directionY == -1;

I have also tried checking if the player was climbing a slope within the last 3 updates, and setting collission.below true if so, but this only mitigates the issue... it still occurs, just less often

any other ideas on how to adress this?

#

and here is the code from determining my velocity when climbing up a slope

void ClimbSlope(ref Vector2 velocity, float slopeAngle)
    {
        float moveDistance = Mathf.Abs(velocity.x);
        float climbVelocityY = Mathf.Sin(slopeAngle * Mathf.Deg2Rad) * moveDistance;

        if (velocity.y <= climbVelocityY)
        {
            if (player.isDashing)
                velocity.y += climbVelocityY;
            else
                velocity.y = climbVelocityY;
            velocity.x = Mathf.Cos(slopeAngle * Mathf.Deg2Rad) * moveDistance * Mathf.Sign(velocity.x);
            collisions.below = true;
            collisions.climbingSlope = true;
            collisions.slopeAngle = slopeAngle;
        }
    }
lean sail
# unreal notch and here is the code from determining my velocity when climbing up a slope ```cs...

did you get this code from somewhere? it seems quite weird and honestly you shouldnt need trig math here, or in many places at all. usually for slope movement you can just project the vector using the normal of what you're standing on.
Also is there an actual problem with it not being grounded for a second? This is kinda just how it'll work if you're moving up a slope. Imagine for example if your move distance was set to a very large number and you were at the top of this slope. It'd look like you were launched up. When you move up the slope, theres nothing checking if you should be moving forward onto that flat surface. That same thing is happening in your code, just to a smaller degree

unreal notch
lean sail
#

that surely is some code. I guess one "fix" would just be having some kind of snap to ground logic where you just manually force the player down if they're close enough to the flat surface. You'd need to code in exceptions so this doesn't run when the player is trying to jump though

unreal notch
#

heres a visual that shows the frame its happening on
again, I believe whats happening is that when moving up this slope, I get more y velocity than I need to reach the flat ground, resulting in my hitbox being beyond the skinWidth threshold needed to set collisions.below true

lean sail
#

i really question what problem this is causing you though. If its just that you can't jump or something because you aren't grounded, you could implement a coyote jump timer. Basically meaning allowing the user to jump for a very small window after not being grounded

unreal notch
#

the problem is almost entirely visual/audio

#

it puts the player intoa falling animation for 1 frame, which also causes a landing sound effect

lean sail
#

I guess snapping the player to the ground then might be a better solution

unreal notch
#

possibly... how would I detect when to do that though?

lean sail
#

Youd have the same issue if you went from a flat surface to another slightly lower flat surface

unreal notch
dire spire
#

anybody know how to fix this?

naive swallow
#

Unity Collab no longer exists. You should probably remove that package

dire spire
#

ah okay

#

i did a clean install of VS and it fixed it but clearly thats what changed haha

naive swallow
#

Looks like the error was in PackageCache so reinstalling it probably cleared the cache as well

shadow wagon
#

does anyone else find that visual studio randomly stops showing errors that absolutely should be shown, until you restart visual studio

#

everything is configured perfectly fine, there's no issue with that

#

i could write some gibberish like Rigidbody2Dfndsfhfhjsf and unity picks up the error but visual studio wouldnt see anything wrong

#

close and reopen VS, suddenly the error appears

naive swallow
#

VS or VSCode? Because VSCode definitely does this often

shadow wagon
#

visual studio

#

whats weird is I tend to notice its only specific to unity types, publicjdkfjsdklf floatdfjshfj foo would always detected

somber nacelle
#

are you perhaps using an older patch of vs? i remember that was an issue a while ago but was then patched, it usually happened when creating a new file or when the solution was just not refreshed when something changed

shadow wagon
#

as far as I know everything is up to date

#

im not at my pc right now, but ive troubleshooted this before and updating was the first thing I checked

#

its almost like it "forgets" how to find errors, yet everything else like intellisense works fine as it still knows all the different types and whatever

shadow wagon
#

its annoying that searching the problem online, only shows posts of people who havent configured the ide at all

sly ivy
#

Hi, trying to make a tycoon game for the phone and making a system that if you watch an ad, it rewards you with 2x multiplier... however, using Ads Legacy, the OnUnityAdsShowComplete doesnt register as complete

#

No errors in console either

steady bobcat
sly ivy
#

Im currently on unity 6

#

following tutorials and they all recommended the legacy one

mossy snow
pastel atlas
#

Is there something about Vector3 which is making it lose precision?? I feel like i'm losing my mind

night harness
#

floats are not precise

pastel atlas
#

bug in the debug logs that screenshot whoops, problem is real though. Clamping gravityFactor to 4 digits helps but doesn't wholely solve

cosmic rain
pastel atlas
#

Yeah need new screenshots

#

My function, console log with what my lil guy is doing

#

I guess I just need to use the System.Math functions to get doubles on everything

#

or work in some new unity script which can do the same thing

cosmic rain
pastel atlas
#

_state.gravityForceApplied and _state.Velocity.magnitude are not keeping pace with each other despite (in theory) being scaled equally

#

In-game it means if I set up two hills next to each other i'll slide down one and not be able to get up the other one fully as the energy isn't being conserved

cosmic rain
#

The energy is not conserved in real life either. There's friction and stuff.
And anyways, it's note entirely clear how/what conclusions you make based on these logs.

#

Do you expect the velocity to change by the same amount as force or something?

pastel atlas
#

Logs are saying the difference between current and last velocity per tick is equal to the difference between current and last gravityForceApplied per tick. More or less, a few precision errors in there. This is good!

But if I check the difference between Velocity.magnitude and GravityForceApplied each tick it keeps increasing

#

must be the gravityDirection vector which is messing it up

cosmic rain
#

Velocity magnitude and gravity force don't have to have a linear relationship.

pastel atlas
#

its the same number, so we expect it to

cosmic rain
# pastel atlas its the same number, so we expect it to

But it's not correct to use the difference between velocity and force in the first place. One is distance / time. The other is distance / (time^2).
So I'm not sure what kind of metric are you expecting to get with velocity - force.

pastel atlas
#

you're correct the naming scheme is a little wack, the whole gravityforce variables are just part of the testing because its not behaving as expected

cosmic rain
vestal arch
#

ik, but just seemed that was missing

sly ivy
misty drift
#

Hi! Could please some one help me understand VContainer better. It has so called LifetimeScope - I can't wrap my mind around it, it's expected to be one for scene or It's good approach to have several ones, for example for each unit on scene?

cosmic rain
misty drift
cosmic rain
#

A third part framework, ok.

#

Lifetime scope usually means how long the object is alive, when it's released/destroyed.

#

In this specific framework it also seems to be a framework specific concept, so you'll need to read the docs.

misty drift
#

yep, docs a bit vague on this. I'm using it without issue at the moment, just don't want to refactor a lot later. Wil continue research -)

cold parrot
#

its important to understand though that DI containers as a pattern do not actually support runtime modification, which makes the pattern unsuitable for gamedev where objects are constantly created and destroyed (in most projects). the unity specific DI containers all try to extend the pattern to support lifetimes, and the lifetime scope is VContainer's idea of that.

#

You get the most benefit and and least headache from DI when you use runtime scopes sparingly (meaning the rules for them are simple and few) or in a very well documented/understandable way that you provide debug-tools and validation for.

#

typically a good reason for multiple lifetime scopes are scenes and large fundamental blocks you have in your game, maybe zones, UI, UI panels etc.

misty drift
#

Yep, I was thinking about separating UI to another scope, since I feel putting all in one getting messy. As for creation of scopes in runtime I've already faced bunch of issues with that and now doing this verey carefully, usually having 1 manager created at the beginning and objects just registering to it to be processed.

cold parrot
#

the biggest danger of DI, as a "beginner" is that you overuse it

#

but its natural to do so when learning such an invasive pattern

misty drift
#

Yep, it's big challenge. I had expirience with DI in Java (a lot), but with Unity it's more like "support tool" rather than cornerstone of your app.

cold parrot
#

in Java (and .NET) DI vibes very differently

misty drift
#

I used it to inject EVERYTHING at first.. ) It wasn't fun)

cold parrot
#

cause in those contexts you generally use it to statically define the creation rules of everything, often from a config file

#

most of that stuff is too basic for use in a program that dynamically changes itself constantly (like a game)

cold parrot
#

just because one uses DI containers, one isn't suddenly and magically solving the global access issue

#

some say that DI containers make it too easy to create dependencies and this is ultimately what can ruin a codebase over time.

misty drift
#

I would say it's not about global access issue. It's about how easy I can get required dependency where I needed and also not lose all configs because I changed name of my class or object.
It's a bit safer to do it in code.

cold parrot
#

and in VContainer you're also supposed to use a MessagePipe for communication. Which is a whole other potential can of worms.