#archived-code-general

1 messages · Page 55 of 1

bronze rampart
#

just thinking out loud now but I guess I have to limit the pool size of objects with rigidbodies to reduce the shear volume of components to get at start. I cant help but feel like im going about this incorrectly

median folio
#

@polar marten That is a cool idea and I was thinking exactly the same thing, the only problem was my manager was specific to this level and I wanted to be able to use this logic with any of my levels.

I just finished trying that subscribing suggestion from melos above and it worked - with the benefit of being able to use my movement objects in any level

@civic fern We have success! Thank you 🙂 I think sometimes I try to over optimize my code before It even needs it. Subscribing to all my movement objects works as you suggested perfectly!

Thank you both for your suggestions!

polar marten
#

this is wrong

#

do this

worthy brook
#

I'm using the 3D starter scene and have added Network Object, Client Network Transform and Client Network Animator components to the players

polar marten
#
class Pool : MonoBehaviour {
 public Projectile projectilePrefab;
 public List<Projectile> pooled;

 void Start() {
  for (...) {
   var projectile = Instantiate(projectilePrefab);
   pooled.Add(projectile);
  }
 }
}

// drag and drop these slots in the prefab's hierarchy
class Projectile : MonoBehaviour {
 public Rigidbody rigidbody;
 public ...;

 void Fire() { ... }
}

@bronze rampart do you see the difference?

worthy brook
polar marten
#

i think you are still #💻┃code-beginner you might want to try some more unity tutorials. i like ray wenderlich's written tutorials

#

now called kodeco

#

you just don't know yet how you can reference things, drop things in slots, etc.

polar marten
bronze rampart
polar marten
#

@worthy brook did you build this terrain?

carmine epoch
#

How do i make it so that when i click with my mouse there is an action, and when i click again it does another action?

dusk apex
#

Depends. What's the pattern thereafter?

worthy brook
civic fern
#

or 1st person

polar marten
#

okay i got you

worthy brook
#

yes it is the 3rd person template

polar marten
#

this is a very very long journey

#

what are you trying to make?

worthy brook
#

basically a PvP isometric fighting game in an arena

civic fern
#

😨

dusk apex
polar marten
#

is this a game played with a controller?

worthy brook
#

it could be played with both M/KB and a controller

hot torrent
#

2021.3.5f1

worthy brook
polar marten
#

meta itself uses 2020.3.18f1

hot torrent
polar marten
#

no

#

you can take a look at this

#

this is a complete example

#

do you have a Quest or a Quest 2?

hot torrent
#

Q2

polar marten
#

this stuff can be really really hard

#

you sort of have to start with exactly one of their working projects

#

because there is a lot of nuance

hot torrent
#

So the random hangups and material crashes happen because of my unity version?

polar marten
#

i don't know why you have random hangups and material crashes

#

those are symptoms of having possibly few, or possibly many, problems in your project

#

last time i went through this diagnostic with someone in the chat, he got really, really mad

#

so i don't mean this to discourage you

civic fern
#

could it be that the project is overloaded?

#

and theres a bottleneck somewhere?

hot torrent
#

?!

polar marten
hot torrent
#

How'd i do that?

polar marten
#

do you use git?

#

is this the first time you are trying your build on the device?

hot torrent
#

nope

#

done it before!

#

And like i said, the project STARTS just fine!

#

it feels random when it happens...

#

once it hung up immediately, and once while i was havinf profiler on, it took very long!

polar marten
hot torrent
polar marten
#

okay

#

do you use any kind of source control or backup your project at all?

hot torrent
#

i have plastic SCM tho!

polar marten
#

okay

polar marten
#

well you have to look for a version of your project that doesn't exhibit the issue, and see what has changed

#

try to find the commit that broke your project

#

i'm sorry but this is the best help i can give!

hot torrent
#

._.""

warm wigeon
#

CharacterController only moving on the X axis?

sacred condor
#

Networking question (Netcode for GO) for y'all.
I'm spawning the player in scene A, then not destroying them as I move to scene B.
Once I get to scene B, I need to set their position to a spawn point.

It looks like it's being set, but when the scene actually loads, I'm still at the same position (xyz) that I was in the previous scene.

This is happening on a local version where I am alone in the lobby as the host

civic fern
# sacred condor Networking question (Netcode for GO) for y'all. I'm spawning the player in scene...

It sounds like the position of the player is not being properly synced between the host and the client when a scene change occurs, the network manager will automatically destroy all objects in the scene, including the player object, and then recreate them in the new scene.

One possible solution is to use a SyncVar to synchronize the player's position across the network, this way when the player moves to a new scene, their position will be automatically synced to all clients. To do this, you can add a SyncVar to the player script that holds the player's position, and then update this value whenever the player's position changes.

#

ahhh

sacred condor
#

It's using DontDestroyOnLoad so we aren't destroying between scenes

civic fern
#

i think its being overwritten by the position data stored in the player object

#

that persists between scenes

#

do you have a spawn point set in each scene?

sacred condor
#

The previous scene doesn't have one, but the scene we transition to does.
What's the best way to set the position?
Currently, we're using this long-ass line
NetworkManager.Singleton.LocalClient.PlayerObject.transform.position = _spawnLocation;

bronze rampart
#

so a PhysicsRaycast is going to look through every single collider in the mask and hierarchy.

For example in a first person shooter you might want to allow the player to shoot just about anything so masking off too much is a problem, but I assume it will also be looking through my hundreds of inactive pooled objects (also my enemies have around 5-10 capsule, box or sphere colliders each so this is a lot of active colliders anyway).

I am considering switching to a single box colliders for most enemies. What other optimization changes can I make to a game that will be casting a ray several times a second?

civic fern
sacred condor
civic fern
# sacred condor The previous scene doesn't have one, but the scene we transition to does. What'...

you can also set the position using networked commands, Instead of setting the position directly as in your code, you can use networked commands to set the position on all clients. You can add a method to your player object's network behavior script (i.e., the script that inherits from NetworkBehaviour) that sets the position of the player object, and then call that method using the Command attribute. This will ensure that the position is set correctly across all clients, not just the local client.

using Mirror;

public class PlayerController : NetworkBehaviour
{
    // Reference to the spawn point transform
    public Transform spawnPoint;

    // Command to set the player position
    [Command]
    public void CmdSetPlayerPos(Vector3 position)
    {
        transform.position = position;
    }

    // Method to set the player position using the command
    public void SetPlayerPos(Vector3 position)
    {
        CmdSetPlayerPos(position);
    }

    // Method to spawn the player at the spawn point
    public void SpawnPlayerAtSpawnPoint()
    {
        SetPlayerPos(spawnPoint.position);
    }
}

Then, in your scene transition code, you can call the SpawnPlayerAtSpawnPoint method on the player object to set its position to the spawn point:

// Get a reference to the player object
PlayerController player = NetworkManager.Singleton.LocalClient.PlayerObject.GetComponent<PlayerController>();

// Set the player position to the spawn point
player.SpawnPlayerAtSpawnPoint();

im not sure the code works since i didnt test it, but it probably needs some adjustments

#

this will ensure that the player object's position is set correctly across all clients in the network

sacred condor
#

That makes sense. I'm noticing this happening even if I'm the only one in the game, so I am both host and client (I guess?) at once.

fading halo
#

How would I go about deleting a specific polygon from a mesh? In this case it'd be basic unity plane.

civic fern
maiden fractal
civic fern
fading halo
#

Alright, so, I currently have 3 vertices that make up a polygon. Now I want to remove said polygon. Or I mean, technically the goal is to remove the square, but currently this is where I am at.
@maiden fractal @civic fern

civic fern
#

and you want to remove the polygon completely?

fading halo
#

The ultimate goal is to dynamically subdivide the mesh based on the distance from the player.

#

Basically, I want to delete the polygon, then make four squares that are then cleaved to triangles as well

#

I currently have a SquarePolygon class that contains the vertices, its position and such.

#

@civic fern

civic fern
#

so you want to use an LOD basically?

fading halo
#

Yes, that's something I already have. My current solution is with tiled planes. But since it's waves, the meshes don't line up.

#

Essentially this from Sebastian Lague, he doesn't explain how it's done though as he decides to go a different route to makes his planets.
@civic fern

civic fern
#

oh yeah ive seen that

fading halo
#

But also for a plane instead of a cube sphere

civic fern
heavy lynx
#

How can i have the object being instantiated, to be intantiated as a child of the game object this script is attached to.

rand = Random.Range(0, templates.blades.Length - 1);
Instantiate(templates.blades[rand], transform.position, templates.blades[rand].transform.rotation);

civic fern
crimson plaza
#

Hey guys, I was wondering if someone could help me determine why this method of turning a player to the mouseposition doesn't work?

maiden fractal
crimson plaza
#
Vector3 mousePosition = mCamera.ScreenToWorldPoint(Input.mousePosition);
Vector3 vectorToMouse = (mousePosition - playerWeapon.position).normalized;
Quaternion lookRotation = Quaternion.LookRotation(vectorToMouse);
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * rotateVelocity);
crimson plaza
maiden fractal
civic fern
# heavy lynx what would that syntax be
rand = Random.Range(0, templates.blades.Length - 1);
Instantiate(templates.blades[rand], transform.position, templates.blades[rand].transform.rotation, transform);

The transform parameter passed as the last argument specifies the parent of the instantiated object. In this case, it's the transform of the game object this script is attached to

civic fern
#

thats too funny

swift falcon
#

Hii

#

Any have a jump script?

swift falcon
#

😦

somber nacelle
# swift falcon Please

this isn't a place to get free code handouts. if you don't know how to code it yourself then search for a tutorial

crimson plaza
#

Also when is it preferred to use the raycasthit instead of the screentoworldposition

somber nacelle
crimson plaza
#

I know that it gives the default 0 position

somber nacelle
#

the third is the distance from the camera

devout solstice
#

Im unable to change any of the variables in the inspector of my struct

somber nacelle
#

of course, i only provided that link because you aren't providing a distance. you've not actually described your issue beyond "doesn't work"

somber nacelle
crimson plaza
#

I was having trouble understanding why the distance from camera mattered

devout solstice
#

Yup

somber nacelle
#

show relevant code

devout solstice
#

It was working before haven't touched it since and it doesnt work now

hexed pecan
#

You mean the Slot list isnt visible in the inspector?

devout solstice
#

No no I can't change any of the variables in the inspector

stuck lotus
#

is there a guide somewhere on how to create an asset pack and structure the files, i just want to be able to add my package using the github url nothin more

devout solstice
#

Like I cant turn the bools on and off

#

Or change the gameobject some of the options are set to

neon junco
devout solstice
#

Oh

#

When tf did I change that

#

oh

#

Yea now it doesnt show up

hexed pecan
#

[SerializeField] goes on a field. RestrictSlot is a type so it takes [Serializable] like you have

devout solstice
#

Finally Im right on something

hexed pecan
#

Can you screenshot the inspector?

devout solstice
#

Those options there I cant change

somber nacelle
#

okay so the issue isn't that they don't show up in the inspector, you just can't change them?

devout solstice
#

Yea

somber nacelle
#

are you perhaps doing anything to the list in OnValidate?

devout solstice
somber nacelle
#

thats why

#

you're overwriting the value immediately after changing it

neon junco
devout solstice
#

oh

#

I see

somber nacelle
#

you change something in inspector then OnValidate is called. what is your OnValidate method doing? it clears the list and repopulates it with the default values you have assigned

devout solstice
#

ItemToDrop is the slot clicked, Item.Key.Item is the Slot in the key value pair, so the if statement is checking if the slot clicked matches the key value pair slot and if so assigns item assigned slot as Item.Value but it doesn't work like that it doesn't seem

#

I have a feeling Im not supposed to be using foreach like this

crimson plaza
#

!cs

tawny elkBOT
#

You can format your multiline code block with C# highlighting! Just add cs to the start of it. Highlighting example below!

class Fluffs : FluffyCat
{
    public void PetCat ()
    {
        Debug.Log ("Petting Cat.")
    }
}
crimson plaza
#
Vector3 mousePosition = mCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, mCamera.nearClipPlane));
            mousePosition.y = 0;
            Vector3 vectorToMouse = (mousePosition - playerWeapon.position).normalized;
            Quaternion lookRotation = Quaternion.LookRotation(vectorToMouse);
            transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * rotateVelocity);
devout solstice
crimson plaza
#

Any suggestions? I've read through the unity forums discussing how to do this and I have done it successfully with raycasthit but not screentoworldpoint

devout solstice
#

then change the z position of the vector returned by the screentoworld

crimson plaza
#

do you mean z in unity or the z-axis like math

devout solstice
#

z coordinate

crimson plaza
#

Because if you meant the latter I already have, so that the player doesn't look up instead

devout solstice
#

z position

crimson plaza
#

What should I change it to?

devout solstice
#

closer

#

if its far make it not far

somber nacelle
#

if this is for 2d you should consider not using LookRotation, especially if you're not providing the same distance from the camera that the player is currently at. of course you've still provided no details beyond just "not working"

crimson plaza
devout solstice
#

Could I have some help once you're done with him Boxfriend?

crimson plaza
#

The mouse is somewhere around the red dot

crimson plaza
#

Is this what you're referring to

#

I thought it meant that switch the camera to orthographic if you're making an entirely 2d game

somber nacelle
#

no, i clearly linked to the Alternate methods section

crimson plaza
#

??? Am I not supposed to use screentoworldpoint then, I'm confused

somber nacelle
#

scroll down to the Alternate methods section

devout solstice
#

Idk whats up with this

somber nacelle
#

can't modify a collection while foreach'ing over it

devout solstice
#

oh shit

ocean oasis
#

you can have your scripts be added through Component > whatever you name the category > Name of script.
I have added a number of my singletons in this list. Is there anyway I could have an object add all the components in that list?

devout solstice
#

Damn, I finally finished this script, been working on it forever now

#

And at some point Im going to find out I didnt set something up right and its not plug and play

echo sleet
#

So ive been doing a lot of reading and thinking on how to organize the gameplay data in my 2D tile based game (think terraria, starbound, whatever)

I was able to make a class that gets the position of every tile in the world and puts them into a 2D array so thats cool, like the tile at index 0,0 is at the vector3int position of 0,0 and so on :P

The next step I think I need to take is create a way to say stuff like oh the tile at position 3,3 is a grass tile and takes this many hits to break and such and I was wondering if anyone had experience with a similar project or just ideas in general. I was also looking into scriptable objects and wondering if it would be smart to make a scriptable object called Tile and it could hold all the information that makes a tile? Hopefully this essay of a question makes sense 😆

latent latch
#

Sounds good. You'll have a Tile class which takes in a TileSO that holds the default values of the specific tile.

#

Allows you to reuse the Tile class while making a bunch of different TileSOs

echo sleet
#

So like the Tile class defines all the data a tile needs to have (the blueprint basically) and then there are TileSO(s) that are the specific tile types like the grass tile or the stone tile?

#

and then I tie all of that to the position array thingy I already set up

cyan dagger
#

Any of you math doers know I can solve my problem? I have a circle, I know Radius and Center and point A, I'm tryna figure out how to get point B.
Point A is always at a random place in the circle and point B is directly down from point A and at the intersecting point of the circle

latent latch
#

This is as far as basic usage of them goes, but it'll allow you to make a bunch of prefabs on the inspector pretty quickly.

echo sleet
#

I think I understand this system enough now so the next step is develop it and see what happens 😆, thanks for taking the time out of your day to discuss this :D

ocean oasis
#

you may also want to consider working in a way where the spawned tile only needs to know what type of block it is, and then asks a little database to present the tile data

echo sleet
#

oh yeah about that

ocean oasis
#

could be easily done with an enum for each tile that corresponds to a database when asking for retrieval

echo sleet
#

Ill look into that method as well since it sounds pretty straightforward, so thanks to you also!

cyan dagger
ocean oasis
cyan dagger
cyan dagger
plain forge
#

Does anyone know if Oculus's eyetracking has a method to detect if eyes are closed or significantly off measurements for coding purposes?

unreal notch
#

The intended purpose of this script is to load all the scenes in my hierarchy that aren't loaded, then FindObjectsOfType, build a dictionary using that array, then close all the scenes that were loaded by this script

#

The script isn't working as is because

string scenePath = SceneUtility.GetScenePathByBuildIndex(i);
Scene _scene = SceneManager.GetSceneByPath(scenePath);```
_scene is coming out with a `_O` on the end of the scene path and I'm not sure why
stuck lotus
#

does anyone here know how to deal with making a custom asset package?

unreal notch
#

is this a scripting question?

stuck lotus
unreal notch
#

I'm not quite sure what you're trying to accomplish, so I dont really know

stuck lotus
#

i dont think there is another chat for this...

rain minnow
#

Are you using assembly definitions?

stuck lotus
#

the asmdef files?

rain minnow
#

Yes . . .

stuck lotus
#

yh

#

in both

rain minnow
#

Make sure you setup the assembly references in the asmdef files . . .

stuck lotus
#

right, i fixed something and now i will try and look into that

pearl trench
#

how can I make this code work for all 3 types of Weapons without trying each one like in the code? All three of them inherit a class called HandHeld, but don't have much in common, they all also have different types of data that they get from scriptable object (the one that i use in TakeDamage(...Weapon.data.damage).

MeleWeapon meleWeapon = interactingObject.GetComponent<MeleWeapon>();
AutomaticWeapon automaticWeapon = interactingObject.GetComponent<AutomaticWeapon>();
SemiAutomaticWeapon semiAutomaticWeapon = interactingObject.GetComponent<SemiAutomaticWeapon>();
if (meleWeapon) {
    TakeDamage(meleWeapon.data.damage);
}
else if (automaticWeapon) {
    TakeDamage(automaticWeapon.data.damage);
}
else if (semiAutomaticWeapon) {
    TakeDamage(semiAutomaticWeapon.data.damage);
}
stuck lotus
pearl trench
#

oh I fixed it thanks

unreal notch
#

hey I'm having a problem with this script still.... the methods work now, they do exactly what I want them to, however, whenever I enter play mode, the dictionary in my scriptable object is getting cleared.... I'm guessing a new instance of the scriptable object is being created? but I dont want that, I just want the data I stored in it in edit mode to be accessible during play mode

https://pastebin.com/3DHGryT4

#

so, this is a general scriptable object question I guess
I'm not entirely sure whats happening here

is a new instance of the SO being created at runtime?
or is the SO just creating a new instance of the dictionary at run time?

if its the latter, how can I make sure the dictionary is initialized in edit mode so I can add things to it in edit mode?

buoyant crane
buoyant crane
unreal notch
unreal notch
#

but yea, all I'm trying to do with the scriptable object is store some data to be used during runtime

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

[CreateAssetMenu(fileName = "SaveSpotReferences", menuName = "ScriptableObjects/Save Spot Refs")]
public class SaveSpotReferencesSO : ScriptableObject
{
    public Dictionary<string, Vector2> saveSpotDict = new Dictionary<string, Vector2>();
}```

This is the entire SO script
#

but yea, I am not sure why the dictionary is being cleared at runtime... iirc the scriptable object shouldn't be gettined cloned, its not a game object, its not in the scene

#

it also has no awake method, which still shouldn't matter because that gets called when the ScriptableObject is created, in editor mode

#

and heres the GUI code

[CustomEditor(typeof(SaveSpotDictBuilder))]
public class SaveSpotDictBuilderButton : Editor
{
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();

        SaveSpotDictBuilder myScript = (SaveSpotDictBuilder)target;
        if (GUILayout.Button("Build Save Spot Dictionary"))
        {
            myScript.BuildListOfSaveGameObjects();
        }
        if (GUILayout.Button("Log Dictionary"))
        {
            if (myScript.saveSpotRefsSO.saveSpotDict.Count > 0)
                myScript.LogDictionary();
            else
                Debug.LogWarning("Dictionary is empty.");
        }
    }
}```
hexed pecan
unreal notch
#

so dictionaries to store data in scriptable objects is just a no go??

#

I'll try storing the data in lists then, and build a dictionary at runtime for my use case and see if that works

hexed pecan
#

Correct, but you can use SerializableDictionary (3rd party) for example

unreal notch
#

I've tried using that library and had issues with it, so I wrote my own implementation, but its flimsy and only does exactly what I need it to do ;;

hexed pecan
#

Hey not everything has to be super generic

unreal notch
#

but I like modular code systems u_u

hexed pecan
#

But yeah if you can conveniently store it in a list and construct it at runtime its fine too

molten thicket
#

Hey guys,

Sorry to interrupt,

I'm looking to import external JS libraries into a Unity Plugin, but google hasn't been too helpful,

Does anyone have a clue on how we go about doing this?

leaden ice
#

Probably easier to just find a C# Library instead or port the JS lib to C#

molten thicket
# leaden ice In WebGL or what?

Apologies I should have added that this is for WebGL yes.

So I've got that covered and working, but my functions have a dependency on BN.JS (Big Numbers)

In JS you would just go require() or import(), but I'm not sure if that is how we do it within a JSLIB?

leaden ice
molten thicket
unreal temple
#

You can bind C# function calls to JS too

unreal notch
#

guess it was just cause dictionaries and scriptable objects dont mix

unreal temple
#

Then assign some globally accessible API to window

#

Then you can just call those functions via C#

molten thicket
#

Thanks for the help guys! this has definitely given me some extra resources to play around with ❤️

unreal temple
#

Just for calling out from C#

#

oh sorry, it looks like there is a way to call them from within the project using .jslib -- my bad!

#

If you want to do anything sophisticated with JS then I'd probably do that in the template (with an npm project) and then do a minimal wrapper in jslib that does the interaction

molten thicket
#

Makes sense

unreal temple
#

But if you just want a few helpers just follow that guide and it will work

molten thicket
#

Do most of the work outside

#

For context I'm trying to import this haha

unreal temple
#

ah doing some crypto shit

molten thicket
#

I apologise

unreal temple
#

hahah

#

Yeah, so chuck that in the template

molten thicket
#

I'm a blockchain developer and playing around with POW and creating gasless TX

unreal temple
#

That header

#

Make a custom template that includes those imports

molten thicket
#

Thanks Rhys that clarifies and helps a lot! I'll jump onto that now.

unreal temple
#

So web3 will liekly attach some objects to window

#

And you can call them from your jslib

#
// your-cool.jslib
mergeInto(LibraryManager.library, {

  MakeCash: function () {
    window.Web3.makeSomeMadCash();
  },
}
using UnityEngine;
using System.Runtime.InteropServices;

public class GameManager : MonoBehaviour {

    [DllImport("__Internal")]
    private static extern void MakeCash();

    void Start() => MakeCash();
}
molten thicket
#

That MakeCash Function

#

xD

unreal notch
#

lists are reliably ordered, right?

unreal temple
#

They're just an array internally

unreal notch
#

I'm working on future proofing my save game system for my metroidvania, and oh man its beena task

unreal temple
#

future proofing is the enemy of progress

unreal notch
#

almost done though, and then I'll be able to add and move around save locations without breaking saves from previous game versions!

unreal temple
#

oh that kind of future proofing

#

No that sounds smart :-)

urban blade
#

how can i make a sprite fade out?

unreal notch
#

in a number of ways.
I prefer using the DOTween library, makes life very easy in that regard

with it, you can do SpriteRender.Sprite.Color.DOFade(endAlphaValue, durationOfFade)

#

other options include writing a coroutine that reduces the a value of the sprite.color over time... using animation cuvres or math or lerp...

urban blade
#

thanks

oak plover
#

i ran into a problem

#

so

#

1

#

i updated my animation 2d

#

and thats the error i get and i cant start my game

#

2

#

wheres the UI option

#

am i stupid

#

can someone help me? ik its not code related but i dont see another channel lmao

maiden breach
#

Maybe it cant compile UI package because of the error? Try fixing that first.

oak plover
#

idk how to fix the error

#

idk what its talking about it poped up after i updated 2D Animations

#

and it was like that before i updated it

#

i updated it due to it not working lol

#

when i say updated i mean update 2d Anim

maiden breach
#

Wait you said it popped up after you updated, but was also there before?

oak plover
#

wdym

#

befoer how

#

what*

maiden breach
#

What do you mean?

oak plover
#

how it came to be, i wanted to do ui so i downloaded package thing, it didn't show up when i right chick in the Hierarchy so i checked inside of In Project for Package Manager and some things weren't updated so i decided to update 2D Animations since its first and then after i did that the error came, i tried reverting the version back didn't help

#

then i updated it again

#

here we are

maiden breach
#

Ok well, from my reading of the error it looks like something in 2D psd importer doesnt get along with your update to 2D animation. Is there an update for 2D psd importer?

oak plover
#

yeah i updated it with Animator after the error to see if it fixes it

#

do i revert them both?

#

nvm

#

cant revert PSD

#

halp :c

maiden breach
#

Im not following what youre doing. Youre not letting me know what steps you have taken and in what order and what works/doesnt work/changes.

oak plover
#

so i told you how i got the error i havent done anything frokm that

maiden breach
maiden breach
#

In package manager you should be able to see previous versions as a dropdown in the list on the left. Go back to what it was before.

oak plover
#

for?

#

2d Anim or PSD

maiden breach
#

Psd first

oak plover
#

there is none

#

only for 2d Anim is ther

#

her

#

here*

bronze rampart
#

I have an object pooling script with several instances that are all behaving as expected but I have one instance that is returning every object in the pool as null, ONLY after reloading. Each reload the objects are recreated and the pool repopulated so this shouldn't be making a difference but I have tried loading the scene in single as a bandaid and this changed nothing.

Everything works as expected the first run of the game and no other instances of this system break. I have made sure the problem persist with other prefabs in this instance and I have added an unbelievable amount of debug statements to the code to try and figure out where the fuck it goes missing but it seems like the pool immediately depopulates itself ONLY in this instance.

the pooling
https://hastebin.com/share/atadegifoy.csharp

context for spawn call
https://hastebin.com/share/fitudinayu.csharp

TYVM for looking through this im pretty exhausted with setting this up

maiden breach
# oak plover

ok give me a second. I'm going to hop on my computer

oak plover
bronze rampart
#

Id edit it in but I cant paste into an edit I guess but here are my debugs in the console

#

im gonna confirm that each list index != null as well

#

at start I mean

#

no the pool gets initialized without any null items

wispy wolf
#

Are collision normals oriented relative to the world or relative to the collider's transform?

maiden breach
#

It's a version mismatch. You need to upgrade your Unity editor version or downgrade to what was working before

#

You can do this through your version control if package manager isn't cooperating

oak plover
#

idk if that helps

#

i think around there

maiden breach
oak plover
#

imma check it

#

what is the annono

#

thing

#

anonymous

#

hi?

maiden breach
#

Unity answers bug

buoyant crane
# oak plover hi?

yeah it’s probably a migration error or something. hi’s got replaced with that

oak plover
#

wait

#

it saying to delete psd

#

doesnt that delete my animations'

#

cause its a dependfencie

#

dependency

maiden breach
#

Several ways to skin the cat. You could also try upgrading Unity version. Or manually adjusting version in manifest.json. Pick the one that works for your project.

oak plover
#

ill try upgrading ig

maiden breach
#

best thing to do is remember how you got yourself into this state and revert. I cannot tell you. I wasn't there.

#

your version control would remember

oak plover
#

version ocntroll?

maiden breach
#

git

ocean pewter
#

is there any issues with using . as a name separator in folder names containing .asmdefs that will bite me later on from some tooling? Like for example, where each folder would contain its own asmdef:

--Assets
  --Scripts
    --MyGame.Client
      MyGame.Client.asmdef
    --MyGame.Client.UI
      MyGame.Client.UI.asmdef
    --MyGame.Common
      MyGame.Common.asmdef
    --MyGame.Editor
      MyGame.Editor.asmdef
deep willow
#

i have a spell system in my game and i need to save the data of each spell. then use that data to add spells to the player's spell inventory. how would i store that data?

oak plover
#

@maiden breach

#

fixed it

#

downgraded
2D Animation to 5.0.4
2D SpriteShape to 5.1.1

maiden breach
#

nice, glad you figured it out

oak plover
#

no we still on ui problem

#

lol

#

anyone know what the package is for ui

#

idk if its this one

maiden breach
#

its that one

oak plover
#

then why isnt the tab shoing up in hirachy

#

nearthe bottom should be a UI

maiden breach
#

yes, seems like a bug. Restart Unity?

oak plover
#

did

#

like hub too?

maiden breach
#

delete Library folder

oak plover
#

or just unity

#

huh?

#

wdym by delete it

#

what would that do?

maiden breach
#

it's Unity generated files. would force it to generate again. And get it right this time.

#

you could try Library/PackageCache first

oak plover
#

ok so how do i delete it

#

imma just delete it

#

just del that?

#

trash and clear?

maiden breach
#

try PackageCache first. It'll be faster and you can always go for the full folder after

#

Library/PackageCache

oak plover
#

wait

latent latch
oak plover
#

del the PackageCashe?

#

that what your saying?

#

just to be clear lol

maiden breach
#

yes, Library/PackageCache

oak plover
#

k

deep willow
oak plover
deep willow
#

and set the spell prefab's data to that spell data

latent latch
#

You can make a temporary database that exists only at runtime

oak plover
#

@maiden breach

#

just says its good?

maiden breach
#

its fine

#

got your menu item?

oak plover
#

ayy got the ui

#

now after 3 hours i can finally put a damn hp bar

#

XD

oak plover
#

wait

#

menu?

deep willow
#

i think ill just use a text file with the data for each spell

#

i might have to encrypt it tho?

#

cause then players could edit the spells?

#

dont know much about encryption tho lol

ocean pewter
#

if its an online game, let them crash. if its a local only game, let them do whatever

#

just an opinion anyway

#

there's also sqlite db but its kind of a pain in unity until you get the gist of including it

#

and they can be encrypted if thats something you want.

deep willow
#

im wondering how to hold data to read from while the game is running

#

like a text file

#

i want to manually add spell data to the file, then grab specific spells from that data

#

can i just use a generic text file for this?

hollow karma
#

ahhhh

#

I'm having mega trouble with the 2d grid stuff in unity

#

is there a way I can just snap two sides of object together?

#

like powerpoint or something

ocean pewter
deep willow
#

ah kk

hollow karma
#

also why does my person snap to an intersection point

#

i mean it makes sense

deep willow
hollow karma
#

but can I have it snap to the sides?

ocean pewter
deep willow
#

so that defeats the point doesnt it?

ocean pewter
#

you want to make edits just free-hand rather than in your code?

deep willow
#

i just want to have data for all spells and create a spell then grab data from one of the spells in the data

#

like at a point in my game, i give the player an option from 3 random spells

#

but i need to hold the data for all spells in the game somewhere

ocean pewter
#

sure, so you could have all your spells or the preselected possibilities in a List<T>, serialize that, read it back and populate the list with the ones you want to let the player select from

latent latch
#

if your data is predefined you dont need to serialize it. If only say you've allowed to create a variation of the spell (in game), then you'd have to save that somewhere for another session.

ocean pewter
#

and really, json is overkill. SerializedObject is perfect for this

#

or a db if you're comfortable with that

deep willow
#

yeah it'll be predefined

ocean pewter
#

basically, if its predefined: probably scriptable object
if its not predefined: database or file

deep willow
#

ahh kk ill look into scriptable object

normal portal
#

im getting this error but i assigned all game objects and stuff, why is this still happening?

#

and its working when im using my script to move it but not working when i want to call a function of that object's script

normal portal
normal portal
#

i tested it out in Debug.Log();

cosmic rain
#

If it throws the error then it is null.

#

What's line 260?

normal portal
#

objects[10].GetComponent<HoverUI>().Show(

#

objects[10].GetComponent<RectTransform>().anchoredPosition = (Vector2)Input.mousePosition+objects[10].GetComponent<RectTransform>().sizeDelta/2; is working

cosmic rain
#

So it's either objects[10] being null, missing a HoverUI component or one of the things in the arguments being null.

normal portal
#

ok

cosmic rain
#

Debug each of them before that line and see what's null

normal portal
#

ok i tested it out it was all my fault

#

at the line that its not needed to get the parent but i still make it gets the parent

#

thanks

deep willow
#

i need to add some ui infront of other ui objects

#

basically to show some choices to the player

#

and they can pick from 1 of 3 spells

#

can i just draw images/buttons on top of other ui?

#

and i need to make sure the player cant click on anything beneath these spells

#

im wondering, could i draw an image over top my whole screen to stop the player from clicking on anything beneath?

teal jetty
#

hi guys 🙂 📕 lib: https://github.com/jjrdk/websocket-sharp#websocket-client

I've had the problem before but I don't know if it's the same!
I was told that it was not in the same thread as unity, but I don't know how I could make it work, I don't see anything in the doc

public class wsManager : MonoBehaviour{
    WebSocket ws;
    void Start (){ 
        ws = new WebSocket("ws://***:3048");      
        ws.OnMessage += OnMessage;
        ws.Connect();

        VideoPlayer videoPlayer = GameObject.Find("VIDEO").GetComponent<VideoPlayer>();
        Debug.Log(videoPlayer); //WORKING

    }

    void OnMessage(object sender, MessageEventArgs e){
        VideoPlayer videoPlayer = GameObject.Find("VIDEO").GetComponent<VideoPlayer>();
        Debug.Log(videoPlayer); // NOT WORKING
    }
}
deep willow
#

why am i getting this error?

#

the names are the same

#

nvm fixed it

knotty pivot
#

Off the top of yer head, would anyone happen to know the algorithm used to interpolate between keyframes in UnityEngine.AnimationCurve? I think it's a cubic hermite spline but if I could get confirmation it'd help a lot. I can't find info on it anywhere online :\

#

Although being the absolute mess I am, I have a feeling I missed something stupid obvious.

humble thistle
#

Would anyone have some insight on how I could clamp the transform.Rotate function?
I'm trying to rotate the camera using the mouse delta y which works perfectly but I need to clamp it and I've really been racking my brain on this

#
{
    public Rigidbody playerRB;

    private Vector3 vel;
    private Vector2 inputVec;

    public GameObject vCameraHandler;

    public float movementSpeed = 5f;
    public float movementSmoothing = .1f;
    public float mouseSens = .75f;
    public float minXCam = -30f, maxXCam = 90f;

    private float mouseDeltaX, mouseDeltaY;
    
    private void FixedUpdate(){
        RotateCamera();
        MovePlayer();
    }

    private void MovePlayer(){
        //vel.x = Mathf.Lerp(playerRB.velocity.x, (inputVec.x * movementSpeed), movementSmoothing);

        vel.x = inputVec.x * movementSpeed;
        vel.z = inputVec.y * movementSpeed;
        vel.y = playerRB.velocity.y;
        
        playerRB.velocity = transform.TransformDirection(vel);
    }

    private void RotateCamera(){
        transform.Rotate(Vector3.up * (mouseDeltaX * mouseSens));
        vCameraHandler.transform.Rotate(Vector3.right * (mouseDeltaY * mouseSens));
    }
    
    //---INPUT CALLBACKS---
    public void onMove(InputAction.CallbackContext ctx){
        inputVec = ctx.ReadValue<Vector2>();
    }

    public void onMouseRotX(InputAction.CallbackContext ctx){
        mouseDeltaX = ctx.ReadValue<float>();
    }

    public void onMouseRotY(InputAction.CallbackContext ctx){
        mouseDeltaY = ctx.ReadValue<float>();
    }

}
#

Specifically the RotateCamera Function

grave raptor
#

having some weird issues with setting variables through animation events
am I understanding it correctly that any value that was used in an animation state can't be changed manually through code later?
any time I try the animator seems to set it back to default immediately, if I turn off "write defaults" on a state it will turn it back to whatever the last animation that used it left it as

gleaming patrol
humble thistle
# gleaming patrol you want to clamp the rotation ?

I've kinda got it figured out and I felt a little dumb. However because I'm using cinemachine it has caused another issue where I have to have it follow a separate game object as I obviously don't want to rotation my character on the x axis

#

But getting the x axis to work weirdly just made cinemachine stop following the rotation on the y axis

#

So I've gotta figure that out... Somehow.

#

Alright so I fixed it by just guessing and I'd like to know if someone can explain to me what the difference between transform.rotation.y and transform.rotation.eulerAngler.y (<- This is the one that worked) that'd be great

#

The line of code is question:
vCameraHandler.transform.rotation = Quaternion.Euler(xCamAngle, transform.rotation.eulerAngles.y, 0);

#

My only guess is that it's because eulerAngles is in world space

#

and that rotation.y would be local

#

But I'd prefer to know why this worked rather than guessing

civic fern
#

there's a million tutorials on how to make your character sprint, dont try and get it spoon fed youll literally hit a wall

civic fern
# humble thistle But I'd prefer to know why this worked rather than guessing

Yes, you are correct. The main difference between transform.rotation.y and transform.rotation.eulerAngles.y is that the former is a single value representing the rotation around the local y-axis, while the latter is a Vector3 representing the rotation in euler angles around the three axes in world space.

The transform.rotation.y returns a float value representing the rotation of the transform around its local y-axis. This value is between -1 and 1 and can be used to get the current rotation or set a new one around the local y-axis only.

On the other hand, transform.rotation.eulerAngles.y returns the rotation of the transform as a Vector3 of euler angles in degrees. This Vector3 contains the rotation around all three axes in world space. By using Quaternion.Euler(xCamAngle, transform.rotation.eulerAngles.y, 0) you are creating a new Quaternion that takes into account the rotation around the local x-axis (xCamAngle) and the rotation around the global y-axis (transform.rotation.eulerAngles.y) while ignoring the rotation around the local z-axis (0).

So, using transform.rotation.eulerAngles.y instead of transform.rotation.y in your code allows you to get the rotation of the transform around the global y-axis instead of the local y-axis, which is what you want in this case.

civic fern
#

♥️ no worries

#

goodluck hf

humble thistle
#

Everything is going great after I figured out that whole issue

civic fern
civic fern
civic fern
storm lynx
#

Hi guys, im not a programmer but I defend myself while coding. Wanted to know more about online multiplayer or singleplayer code in Unity or Unreal. As the title of this message, if anyone have some knowledge about it please message me.

civic fern
#

the docs would be a good start to learn about multiplayer code

teal jetty
#

Hi, you already had errors in the build ?, for example
⚠️ error CS0246: The type or namespace name 'WebSocketSharp' could not be found (are you missing a using directive or an assembly reference?)
I try to build it in webgl, and yet it takes into account because I am under photon, but when you play with the editor no error and WORK?

using UnityEngine;
using UnityEngine.Video; 
using WebSocketSharp;
public class wsManger : MonoBehaviour{
    WebSocket ws;
    bool shouldStartVideo = false;

    void Start (){ 
        ws = new WebSocket("ws://***");      
        ws.OnMessage += OnMessage;
        ws.Connect();
    }   
}

#

What I don't understand is that it works very well in the editor.

civic fern
# teal jetty Hi, you already had errors in the build ?, for example ⚠️ `` error CS0246: The ...

The error you are seeing is because the WebSocketSharp namespace is not being recognized. This is likely because you have not added a reference to the WebSocketSharp library in your project.

To resolve this error, you should make sure that you have added the WebSocketSharp.dll file to your project's references. Here are the steps to do this:

Download the WebSocketSharp.dll file from the WebSocketSharp GitHub page.
In Unity, go to the Assets menu and select Import Package > Custom Package.
Navigate to the location where you saved the WebSocketSharp.dll file and select it.
Unity will import the package and add the WebSocketSharp.dll file to your project's references.
After you have added the WebSocketSharp.dll file to your project's references, you should be able to use the WebSocketSharp namespace in your code without seeing the error.

teal jetty
#

but I will try again to import it!

#

because the fact that it works on the editor I find it weird

civic fern
#

hm

mellow sigil
#

You sound a lot like ChatGPT

teal jetty
mellow sigil
#

I wasn't talking to you

teal jetty
#

chatgpt is rather a beginner, you should not use it kekw

teal jetty
#

@civic fern can't import dll

#

but in any case it is already, it works very well in the editor and in my opinion photon uses it so idk

civic fern
#

have u tried adding the assembly to your webgl build settings manually?

teal jetty
#

in player settings ?

civic fern
#

in scripting define symbols

teal jetty
#

i want to cry, im sure its stupid error

#

1 day im stuck, and any forum can't find my error

#

@civic fern any update ? 🙂

#

Ok i build in windows, work but not in webgl.

cosmic rain
#

Take a screenshot of the dll inspector

median folio
#

Hello again, I've come across another architecture type issue that I'm trying to decide how to tackle.

As before each of my levels has a different 'level manager' script to handle the logic. When the user scores a point the score gets updated inside of the level manager.

I then want to fire an event to let my other objects know a point has been scored. The problem is that I don't want to make a direct reference to a particular 'level manger' as I want to be able to use the same event system on each level.

For this purpose would implementing an interface on my 'level manger' be a good solution? Something like IManager, the listener objects could have a serilaized field to reference IManager and could then listen for the events?

ruby fulcrum
#

why is it that sometimes the grenade (the object the code below is under) rotates downwards instead of upwards as intended?

values:
maxXAimDir = 302
xDirIncrement = 30

if (isAiming)
        {
            if (transform.localEulerAngles.x <= maxXAimDir)
            {
                transform.localEulerAngles += new Vector3(xDirIncrement * Time.deltaTime, 0, 0);
            }
            
            generateLineTrajectory();
        }
    }
mossy snow
#

the values returned by localEulerAngles are probably flipping on you. Either store the last used rotation and always assign and never read back, or (preferably) use a Quaternion instead

ruby fulcrum
#

do i use Quaternion.AngleAxis

mossy snow
#

you can, or Quaternion.Euler

ruby fulcrum
mossy snow
#

no, the best solution is to avoid using euler angles entirely. There are multiple ways to represent a given rotation using euler angles, so code using logic that assumes it will be consistent is prone to breaking

ruby fulcrum
#

so replace localEularAngles with localRotation?

mossy snow
civic fern
#

another solution could be to use a messaging system such as the Observer pattern u can decide which works best for you though

rough fern
#

Is there an easy way to check the length of a cross section of a 2D collider?

median folio
#

Hi @civic fern , I couldn't get the interface to work for some reason - it couldn't access the events on the manager.

My solution was to have the level manager inherit from a base manager class which works which had the event on it instead, what do you think?

I've heard of the observer pattern but never looked into it, will check it out thanks!

iron basalt
#

(general c# not using unity:)

with Console.ReadKey, the entire program waits for an input before continuing. is there a way to have an event similar to .ReadKey instead?

For example, after 5 seconds of no input from ReadKey, I would like to have some random .WriteLine text, BUT if i put the ReadKey in an async method, after the .WriteLine is done, the program exits without ever getting the ReadKey

tawny elkBOT
iron basalt
#

im considering to restructure my program, so that anything i want to happen ends up in a queue, then the entire program in a do while loop (exiting the loop exits the program).

then if theres just waiting for the input, the program will just loop over nothing repeatedly, still waiting for the ReadKey from the async Task

iron basalt
#

i know some people will be eager to answer my question here, so ill just leave it up here

vague slate
#

Any advanced Rider user?
How to make it ignore PackageCache folders for code analysis? So annoyed it scans literally all packages

civic fern
dense knoll
#

how i can make the player not move on Y?

civic fern
hollow junco
#

where can i find a good tut about swarm pathfinding algorithms

median folio
civic fern
fervent furnace
#

are there guys using ternary heap? i am going to implement one for my a star

#

is it really faster than binary version? i know that it makes use of cache
oh i test it binary is faster

grave raptor
#

sorry for the ping lol basically just wanted to say thanks because that did set me on the path to figure that out

eternal geyser
#

guys i have a problem, unity is broke idk why? My code is perfect why does it say that it doesnt exist such code

#

trying the whole day all sort of stuff but it doesnt work

simple egret
#

Does the error also appear in your Unity Console?

eternal geyser
#

yes

simple egret
#

Ah, your own class is named Animator, it's picking up that one instead of Unity's

eternal geyser
#

alirght il try it out thanks

simple egret
#

Refers to the class itself

eternal geyser
#

omg its really becouse of that

#

so stupid omgggg

eternal geyser
reef compass
#

Anyone can help me?

eternal geyser
#

with what?

simple egret
#

You need to ask a question in order to get answers

reef compass
#

Where I can share Screen

eternal geyser
#

on discord?

reef compass
#

I want to share screen

simple egret
#

Nowhere, you can record and post a video of it here

eternal geyser
#

do you mean like screenshot?

simple egret
#

Voice channels are disabled for obvious moderation reasons

fervent furnace
#

can the compiler compiles it?

#

i lag

reef compass
#

And When I click Space

simple egret
#

Please follow the !code posting guidelines

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

reef compass
#

😦

dense knoll
#

how i can make the player not move on Y

simple egret
reef compass
#

How can I fix that

simple egret
#

First, by confirming it's what's actually happening

#

Don't go fix an issue that doesn't exist, always debug and verify that's the true cause

knotty pivot
simple egret
# dense knoll how i can make the player not move on Y
movementDir.y = 0;
movementDir.Normalize();

Normalize required, as you stripped out the Y axis, the other two's lengths must be recalculated so you don't go slower if you look up/down. If you want that to happen though, remove the normalization.

bronze crystal
#

when i land i can't jump anymore ```void Jumping()
{
// Check if the player can jump
if (isGrounded && Input.GetKeyDown(KeyCode.Space))
{
// Set the player's Y velocity to the jump force
GetComponent<Rigidbody>().velocity = new Vector3(0f, jumpForce, 0f);

        isGrounded = false;
    }
}

private void OnCollisionEnter(Collision collision)
{
    Debug.Log(isGrounded);
    if (collision.gameObject.CompareTag("Ground"))
    {
        isGrounded = true;
    }
}

private void OnCollisionExit(Collision collision)
{
    Debug.Log(isGrounded);
    if (collision.gameObject.CompareTag("Ground"))
    {
        isGrounded = false;
    }
}```
vagrant blade
#

Log your if statement in your collision function.

bronze crystal
# vagrant blade Log your if statement in your collision function.

like this: ```private void OnCollisionEnter(Collision collision)
{
Debug.Log(isGrounded);
if (collision.gameObject.CompareTag("Ground") && isGrounded && Input.GetKeyDown(KeyCode.Space))
{
// Set the player's Y velocity to the jump force
GetComponent<Rigidbody>().velocity = new Vector3(0f, jumpForce, 0f);

        isGrounded = false;
    }```
vagrant blade
#

No? Log to check if your if statement is running. The previous code you showed.

bronze crystal
#

i have a debug log already

#

when i re-enter, grounded is still false.

simple egret
#

It's very unlikely you'll press Space at the very millisecond the collision happens

#

This code runs once, so to be able to go inside that if statement, you would need to press (press, not hold) Space at the very moment this method runs

maiden breach
#

Skill-based jumping

vagrant blade
bronze crystal
#

i dont get it isGround should return to true and activate ability to jump again.

vagrant blade
#

It's not turning true because your if statement is not running allowing it to turn true, but you would know this if you logged it.

simple egret
#

Even if it passed into the if statement, it would set it to false immediately, as it's what you tell it to do: isGrounded = false;
You need to post the entire method, as nothing here sets that bool to true

bronze crystal
#
    {
        if (collision.gameObject.CompareTag("Ground"))
        {
            isGrounded = true;
            Debug.Log("isGrounded is: " + isGrounded);
        }
    }```
#

i logged it i receive nothing

vagrant blade
#

Well, there you go.

simple egret
#

Also log outside that if statement to see if this is actually getting called at all. If you did that already, and it's called then what you collided with didn't have the Ground tag

bronze crystal
#
    {
        Debug.Log("Ground hit!");
        if (collision.gameObject.CompareTag("Ground"))
        {
            isGrounded = true;
            Debug.Log("isGrounded is: " + isGrounded);
        }
    }```
#

i do hit the ground

#

aaah iam so stupid

weary kelp
#

anyone know how to create a dropdown in the inspector? rigidbody for example:

full scaffold
#

that isnt a dropdown

weary kelp
#

what is it then

somber nacelle
#

that's a foldout. and you can do that either with a custom inspector, the Foldout or Expandable attribute from Naughty Attributes, or serializing a non-UnityEngine.Object field (like a plain class or struct)

weary kelp
#

ok thx

full scaffold
#

pretty sure it's a toggle

rancid kindle
#

hey so i was making a quit scene in unity where when pressed a button ingame itll redirect to the main scene im using scene manager, ive put all scenes on build and im using the loadscene code too

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class QuitScene : MonoBehaviour
{ 

    public void changeScene()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 0);
    }
}

my scene still doesnt seem to load even after ive pressed the button tho, ive even made proper buttons with it.. if anybody knows the reason why this might be happening pls do help me out..
thanks!!

somber nacelle
#

SceneManager.GetActiveScene().buildIndex + 0
what scene do you think this will point to?

rancid kindle
#

the 0th scene

somber nacelle
#

that is true only if you are currently on the scene at index 0.

rancid kindle
somber nacelle
#

if you just want to go directly to the scene at index 0 then just pass 0 instead of passing the current index plus 0

rancid kindle
#

ok lemme try that

#

nah its still not workin

somber nacelle
#

did you make sure to save? and have you considered adding a Debug.Log message to make sure the method is actually being called?

rancid kindle
#

let me actually log it yeah

#

it doesnt even log it

#

when i click the button

#

that means the button isnt even triggering

somber nacelle
#

do you have an event system in the scene?

rancid kindle
#

i do

somber nacelle
#

during play mode it has a preview you can view to see what is being clicked on

rancid kindle
#

yeah

#

when i click on the button like that it converts eligibleToClick true

#

but like its true everytime i click the scene anyways

somber nacelle
#

are you actually looking at the preview or are you looking at the properties on the event system? because i'm referring to this

rancid kindle
#

yeah

#

im lookin at this

somber nacelle
#

and you see that the button is appearing in there when you click on it?

rancid kindle
#

well nothing shows beside the selected:

#

its just that the eligibleForClick turns true

#

thats the only change when i click it

somber nacelle
#

is the button actually interactible?

rancid kindle
#

well its a button so it should be

somber nacelle
#

that doesn't prove that it is actually interactable though, you realize there's a property that controls that right? also make sure your text isn't a raycast target or whatever so it doesn't block the raycast from the mouse

rancid kindle
#

let me check the raycast target i might not actually checked that

#

okay it isnt a raycast target

somber nacelle
#

okay so is the button interactable

rancid kindle
#

it isnt a raycast target

somber nacelle
#

well that probably should be. the text shouldn't be

rancid kindle
somber nacelle
#

look at the button component?

rancid kindle
#

lemme

somber nacelle
#

but again, your image probably needs to be a raycast target since that is what you are clicking on

rancid kindle
#

i tried that too

crystal holly
#

hey guys, i have a heatmap as a plane with vertex colors and i'd like to convert this to a texture to be able to use HDRP Decal Projector to project it down on some other geometry. could anyone point me in the right direction?

rancid kindle
#

didnt work

somber nacelle
rancid kindle
#

ill ask there

#

and yes the button is interactable

craggy cedar
#

Can I reuse an OnDrawGizmosSelected() from an object in a CustomEditor of a different class?

hexed pecan
leaden ice
#

e.g. make a public void DrawMe() and call it in both gizmo methods

craggy cedar
#

Alright, thanks

#

It seems that I can't use Gizmo drawing functions outside OnDrawGizmos(Selected)

leaden ice
#

as long as you're calling your function from one of those methods

craggy cedar
leaden ice
#

not in OnSceneGUI

craggy cedar
#

Editor scripts don't inherit OnDrawGizmos

leaden ice
#

I thought you wanted to do it from another script's OnDrawGizmos

craggy cedar
#

lol

#

not in the editor script but the base script

shadow geyser
#

I can't for the life of me find out why this is working but also isn't at the same time
the following three snippets of code work

webrequest and deserialize
https://paste.ofcode.org/wHzJxY3WcUNHr2WUjBkg3r

response
https://paste.ofcode.org/TyBPAeTMeqsLrgXgXscHTV

C# class
https://paste.ofcode.org/KA79kwtCRyhzYBF8KFxtQG

and now the next snippets don't work it gives "ArgumentException: JSON must represent an object type." error

webrequest and deserialize
https://paste.ofcode.org/AZkRv3DW7Ue7DhKCXJaACU

response
https://paste.ofcode.org/atWhMtjpMP5wR3MZ2PDmDD

C# class
https://paste.ofcode.org/zre32iGjcZS4ZQwBQ35PLi

#

The error is at
Collected[] collected = JsonUtility.FromJson<Collected[]>(webRequest.downloadHandler.text);

cosmic rain
#

I don't think you can de/serialize an array like that with JsonUtility.

shadow geyser
#

That's what I find online, but the first three snippets work

somber nacelle
#

JsonUtility does not support a collection as the root object. it has to be part of some other object (like a class or struct)

shadow geyser
cosmic rain
shadow geyser
#

one hundred percent

#

I use the dictionary later to create ui elements

cosmic rain
#

It shouldn't work

#

In fact, it's weird that it even compiles

#

Add a debug after that line and see if it prints:

Card[] card = JsonUtility.FromJson<Card[]>(webRequest.downloadHandler.text);
shadow geyser
#

ok actually wait I dont actually run that code so no it probably doesnt work

#

ok I see I just assumed that code was working before

#

when in fact it was different code that adds the root object, inner peace restored

dim umbra
#

I'm trying to make an explosion script that gives every object near it velocity away from it. I've done everything else except the actual part where I set the velocity of each object (https://pastebin.com/1kekHiwt). How would I do that?

#

Would also like if the distance from the radius had some effect on the velocity

somber nacelle
#

you can get the direction from this object to the colliders returned by the overlapcircle then normalize that direction and multiply it by the amount of force you want to apply. then you can also use AddForceAtPosition on each rigidbody so add force from the position of the explosion, that way you get consistent results from everything affected

#

or instead of AddForceAtPosition you just use AddForce

boreal condor
#

I'm having an issue serializing properties

NullReferenceException: Object reference not set to an instance of an object
UnityEditor.EditorGUILayout.IsChildrenIncluded (UnityEditor.SerializedProperty prop) (at <abcf38996a474f319c10e3e20ff8cc9f>:0)
UnityEditor.EditorGUILayout.PropertyField (UnityEditor.SerializedProperty property, UnityEngine.GUILayoutOption[] options) (at <abcf38996a474f319c10e3e20ff8cc9f>:0)
Gann4Games.RagdollBuilder.Editor.RagdollBuilderEditor.DisplayPhysicsOptions () (at Assets/Gann4Games/RagdollBuilder/Editor/RagdollBuilderEditor.cs:65)
Gann4Games.RagdollBuilder.Editor.RagdollBuilderEditor.OnInspectorGUI () (at Assets/Gann4Games/RagdollBuilder/Editor/RagdollBuilderEditor.cs:58)
UnityEditor.UIElements.InspectorElement+<>c__DisplayClass59_0.<CreateIMGUIInspectorFromEditor>b__0 () (at <3dda2f35da2d49d2a1d47add1e2ff65c>:0)
public class BaseClass : MonoBehaviour {
        [Header("Physics Settings")]
        public float totalMassToDistribute = 75;
        public float baseDrag = 0;
        public float baseAngularDrag = 0.05f;
}

[CustomEditor(typeof(BaseClass))]
public class BaseClassEditor : Editor {
        private BaseClass _target;

        private SerializedProperty _totalMassToDistibute;
        private SerializedProperty _baseDrag;
        private SerializedProperty _baseAngularDrag;

        private void OnEnable()
        {
            _totalMassToDistibute = serializedObject.FindProperty("totalMassToDistibute");
            _baseDrag = serializedObject.FindProperty("baseDrag");
            _baseAngularDrag = serializedObject.FindProperty("baseAngularDrag");
        }

        public override void OnInspectorGUI()
        {
            DisplayPhysicsOptions();
        }

        private void DisplayPhysicsOptions()
        {
            EditorGUILayout.PropertyField(_totalMassToDistibute); // I am getting an error in this line
        }

}
dim umbra
#

I can paste thaqt if you want

somber nacelle
#

no, i will not help you fix code that was AI generated

dim umbra
#

Ok

reef compass
#

How to type OR in Unity

crystal holly
reef compass
#

Operator Can't be applyed

somber nacelle
somber nacelle
swift falcon
#

im trying to make this button open the file explorer and set this raw image to whatever was selected, how can i open the file explorer in code?

somber nacelle
dim umbra
somber nacelle
#

a vector2. direction is just (endPosition - startPosition)

dim umbra
#

Ok

swift falcon
somber nacelle
#

then maybe consider mentioning that as a requirement next time

crisp lichen
#

how can i get that fourth text to wrap? im using horizontal layout group, chatgpt tells me theres an "overflow" option to change to "wrap" but its not existing

swift falcon
crisp lichen
dim umbra
# somber nacelle a vector2. direction is just `(endPosition - startPosition)`

It seems to just barely push, even when the strength is set super high. I don't think I'm doing this right

if (c.gameObject.TryGetComponent<Rigidbody2D>(out Rigidbody2D rb))
            {

                Vector2 direction = rb.transform.position - transform.position;
                direction = direction.normalized * explosionStrength;
                
                rb.AddForceAtPosition(direction, transform.position);
            }

somber nacelle
#

i'm guessing you probably overwrite velocity immediately on the object

dim umbra
hexed pecan
#

Is the rb on a different object?

dim umbra
#

Oh are those meant to be reversed?

somber nacelle
#

no, that's correct

hexed pecan
#

Probably not. I was just missing context

somber nacelle
#

but you are overwriting velocity on the player which means adding force or even modifying its velocity here isn't really going to do much ofanything

dim umbra
#

I don't really see where, I never set it to a specific number anywhere, I always just add or subtract things from it

hexed pecan
dim umbra
#

Slows down player if they are above terminal velocity

#

but I wrote it wrong

#

now that i look at it

hexed pecan
#

Yeah I see youre limiting the velocity but that one's wrong

dim umbra
#

Just needs to be + instead of -

uncut tundra
#

Can someonne tell me how to fix this error: NullReferenceException: Object reference not set to an instance of an object
Com.HighFiveGamesStudio.GetYoGuns.Motion.FixedUpdate () (at Assets/Scripts/Motion.cs:74)

This is my code: https://pastebin.com/2HBUYq8U

dim umbra
uncut tundra
#

k

dim umbra
#

please

idle saddle
#

Any idea why my sprite is spinning while the box collider isnt when I add torque?
rigidbody.AddTorque(impulse, ForceMode2D.Impulse);

hexed pecan
uncut tundra
#

i have initialized everything on that line

#

Brooo, Welton shows us how to setup a scene for a first person shooter and manages to get the motion working...

Over the course of the next couple weeks, Welton will be teaching us how to make our very own first person shooter which will include tutorials on motion, weapon systems, and multiplayer networking! If there's something specific you'd...

▶ Play video
hexed pecan
#

Are you sure you don't have duplicate objects with this script?

uncut tundra
#

nope

hexed pecan
#

Does the object you assigned this script to have a rigidbody component?

uncut tundra
#

yes

hexed pecan
#

The error is telling you are wrong.

hexed pecan
uncut tundra
#

im sure

hexed pecan
#

Type t:motion in your scene's search

#

And screenshot the search results

uncut tundra
#

is it this

hexed pecan
# uncut tundra is it this

Put cs Debug.Log($"Has rigidbody: {rig != null}", gameObject);
Before the line that errors, and see what it prints when you play

hexed pecan
uncut tundra
#

oh

#

and it didnt print anything

hexed pecan
#

Did you put the log before the error?

uncut tundra
hexed pecan
#

It needs to be before. If you get an error, that line is never reached

dim umbra
#

Those quotes look messed up

uncut tundra
#

the start method is befor the other method

hexed pecan
dim umbra
uncut tundra
#

im using the super editor plugin for unity

#

so that might be why

hexed pecan
dusk geode
#

is the default physics engine deterministic now or not ? Conflicting information online

hexed pecan
#

Look at the first error you get.
Something goes wrong in Start, and the rest of Start doesn't execute. Therefore your rig doesn't get assigned

hexed pecan
# uncut tundra

Actually, you can literally see the error in this screenshot..

dim umbra
#

It also seems to push even if it's not in the radius?
Nvm, finally solved it. Apparently when using void Awake it activated the explosion effect before I could set its values. Changing it to void Start fixed it

uncut tundra
#

the weird quotes is from the plugin in unity, in vscode its normal

hexed pecan
#

Alright but fix the error in your Start method

uncut tundra
#

what error

hexed pecan
uncut tundra
#

ohhhhh

#

its something todo with assigning the fov because as soon as i comented the line that sets the base fov, everything works

hexed pecan
#

You most likely haven't assigned normalCam

uncut tundra
#

i changed something in the camera earlier

hexed pecan
uncut tundra
#

i just reassigned the camera

#

and now it works

hexed pecan
#

Noyce. Next time remember to look at the first error you get

uncut tundra
#

yep

#

thanks Osmal

weak mortar
hexed pecan
leaden ice
hexed pecan
#

Yeah was about to ask about that field initializer..

elfin tree
#

How can I go about Instantiating a cube prefab right next to another one? Same question about on top, below or behind, thanks!

hexed pecan
#

Get that offset with the other object's transform.up/right/forward

#

Multiply with -1 to get down/left/back

elfin tree
#

Wouldn't it be position rather than transform?

buoyant crane
elfin tree
#

hmm, so 2, 2, 2, no good?

buoyant crane
elfin tree
#

so * cubeScale

proper pier
#

Can you run a coroutine in a for loop?

buoyant crane
proper pier
#

Cause I tried and my index is acting very odd

#

I have a for loop and every iteration I have it yield return null

#

But the index is counting down for some reason and it’s also not reaching the maximum index

buoyant crane
#

show the code

proper pier
#

Ok

#

Give me a couple

#

let me also send a pic of the console

#

its starting at random values and then going down to 0

tall lagoon
maiden breach
heavy lynx
#

What exsactly does this error mean and how can i fix it?

fervent furnace
#

yield return

simple egret
#

You cannot yield as it returns void

heavy lynx
#

ohhh, is there a way to recreate the waitforseconds effect

fervent furnace
#

maybe you can start a coroutine and perform setbool(false)

elfin tree
#

Hmm, so I tried doing this, yet second cube's Y position is 0.5, even though it should be 1. Is it a local vs global position type of issue?

buoyant crane
# proper pier

can you share more or all of the script? there’s not enough information

proper pier
#

ok

elfin tree
#

I'll rename it cause it's another solution at this point

proper pier
#

actually im kinda busy rn so I'll continue this discussion later, sorry

buoyant crane
fervent furnace
#

the transform of your gameObject's parent affect the transform of spawned object

buoyant crane
#

ah, didn’t know that

elfin tree
#

But when you look at the position numbers in console (not inspector) it is 1 somehow.

elder temple
#

Hey, is there any way to use oncontrollercolliderhit() as oncollisionexit()?

elfin tree
#

Damn..

#

Thanks

swift falcon
#

hi everyone. I have a player prefab for Photon PUN and my questions is how can i get a component from a Prefab? i need to get a renderer to change the material and so on

idle saddle
#

Any idea why the parts are spinning like crazy?
Im just adding force to rigidbodies with circle colliders...

hexed pecan
idle saddle
hexed pecan
#

In that gif?

idle saddle
#

yepp

hexed pecan
#

Are the rigidbodies a child of anything, or is there any other script that could rotate them?

hexed pecan
# idle saddle

What if you try with a normal friction value like 0, 0.5 or 1

idle saddle
#

with 0 they dont spin but slide.
with 1 they spin

idle saddle
hexed pecan
#

My point being, 10k friction is probably causing some anomalies

idle saddle
#

spinning, but they stop after some time

#

but still spinning like crazy

hexed pecan
#

Does the ground have some crazy friction number too?

idle saddle
#

no

#

no material assigned there

#

just a plain box collider

hexed pecan
#

Not sure what is going on then. I would start with lowering the crazy numbers like 1000 as angular drag

uncut tundra
#

hi, im trying to make a pistol spawn in front of the player, but it keeps spawning beside the player. this is my code https://pastebin.com/7R2T8NUN

hexed pecan
#

I would start with checking that it's actually facing forward in the player's local space

idle saddle
uncut tundra
hexed pecan
#

Or is that the thing you tried

uncut tundra
#

ive changed it to multiple numbers, the gun is always facing the right of the player

hexed pecan
#

Is it a child of the player?

uncut tundra
#

the weapon parent is a child of the player and the gun is a child of weapon parent

hexed pecan
#

Is any other script modifying the rotation/position of weaponParent?

hexed pecan
uncut tundra
#

the look scrip changes the x rotation of the gun so the gun always loks up and down with u

hexed pecan
#

Not vertical

#

That's probably where you are going wrong

uncut tundra
#

y i mean like up and down

hexed pecan
#

You want X angle to look up and down

uncut tundra
#

i just commented that line btw

hexed pecan
#

Imagine pushing a pencil through an apple from the top to bottom. That's your Y axis.
Now spin the apple around. It's going to rotate side to side, not up and down

uncut tundra
#

i know

hexed pecan
#

No need to edit the message afterwards... Now the whole thing just looks confusing

uncut tundra
#

i said y because i read mouse y and went with that

somber nacelle
# uncut tundra

don't multiply mouse input by delta time, mouse input is already frame rate independent and anyone teaching otherwise is wrong. when you remove that make sure to lower your mouse sensitivity variable both in the script and the inspector

uncut tundra
#

aand also cause y pos is up and down

hexed pecan
#

Yeah well you literally said Y rotation which normally means Y angle rotation.

uncut tundra
somber nacelle
hexed pecan
uncut tundra
#

ok

idle saddle
hexed pecan
uncut tundra
#

figured out my problem, the look script sets the camera rotation to the weapon parent, and i checked the camera and aperently the camera y rotation is set to 90

hexed pecan
#

How do you not notice your camera being rotated 90 degrees though?

#

While playing

uncut tundra
#

i didnt

#

i stopped the game and some time when i was making the game i set the cameras rotation to 90 degrees

#

in the inspector

idle saddle
#

hmm

orchid bane
#

Can anyone help me find why this method causes stack overflow on the recursive line? It is for A* pathfinding.

void CalculateCost(Node nodeInCheck, Dictionary<Node, int> costs, int price) 
{
  if (costs.ContainsKey(nodeInCheck)) costs[nodeInCheck] = price;
  else costs.Add(nodeInCheck, price);
                
  foreach (var neighbour in GetAllUnoccupiedNeighbours(nodeInCheck))
  {
    if (costs.ContainsKey(neighbour) && costs[neighbour] >= price + 1) continue;
    CalculateCost(neighbour, costs, price + 1);
  }
}```
Given that GetAllUnoccupiedNeighbours works correctly.
knotty sun
#

because GetAllUnoccupiedNeighbours is not working as you think, log the returned count and find out

orchid bane
knotty sun
#

because a count > 0 will cause the stack overflow eventually

orchid bane
#

wut? Its entire purpose is to return count > 0

knotty sun
#

then why are you surprised it gives a stack overflow?

orchid bane
#

Because I think this

if (costs.ContainsKey(neighbour) && costs[neighbour] >= price + 1) continue;```
must prevent the overflow
knotty sun
#

maybe, but have you actually checked it does?

orchid bane
#

As much as I can figure out from exceptions, it doesn't

#

But why...

#

It's the question

knotty sun
#

it's your code, not mine, debug the values rather than just assuming and guessing

maiden breach
#

@orchid bane Are you marking the current node as visited so you don't come back? After all, it is the neighbor of its neighbors.

orchid bane
knotty sun
mossy snow
#

you might not have the usual stack overflow cause, i.e. infinite recursion. It might simply be that your search space is too large, so you exhausted the stack. How many nodes are you searching?

orchid bane
#

Logically, it can't be over 50

#

I mean mustn't be

#

I can somewhat believe 20, but not 50

eager fulcrum
#

Hey

#

I have a weird problem with randomness

#

screenshots from 2 clients

#

both obstacles and units are placed randomly

leaden ice
eager fulcrum
#

units have the same positioning

#

but obstacles dont

#

UnityEngine.Random.InitState(seed);

#

I'm doing this in my GameController

#

and

#
public void SpawnObstacles(List<BattleGridObstacleData> obstacles, Transform parentTransform)
        {
            UnityEngine.Random.InitState(MultiplayerManager.instance.Seed);
            IsReady = false;
            
            var spawnedObstacles = new List<BattleGridObstacle>();
            var obstacleLockedNodes = new List<HexNode>();

            foreach (var obstacle in obstacles)
            {
                var node = GetNodeForObstacle(obstacle, obstacleLockedNodes);

                if (node == null) continue;
                obstacleLockedNodes.Add(node);

                var battleGridObstacle = _battleGridObstacleFactory.Create(obstacle, node, parentTransform);
                spawnedObstacles.Add(battleGridObstacle);
            }

            Timing.RunCoroutine(DelayLockNodesFuckUnity(spawnedObstacles));
        }

        private HexNode GetNodeForObstacle(BattleGridObstacleData obstacle, IReadOnlyCollection<HexNode> hexNodes)
        {
            var node = _battleGrid.HexGrid.GetNodes()
                .Where(x => hexNodes.All(z => z.GetDistance(x) > 3) && CanPlaceObstacle(obstacle, x))
                .OrderBy(x => UnityEngine.Random.Range(0.0f, 1.0f))
                .FirstOrDefault();

            return node;
        }
maiden breach
eager fulcrum
#

I do InitState() again in the script that spawns obstacles

leaden ice
#

Use a Stack

#

Or Queue

eager fulcrum
#

and for some reason Random.Range for spawning units works the same on both clients

#

but random.range is different for obstacles

leaden ice
eager fulcrum
# leaden ice Where's your obstacles list come from
private HexNode GetNodeForObstacle(BattleGridObstacleData obstacle, IReadOnlyCollection<HexNode> hexNodes)
        {
            var node = _battleGrid.HexGrid.GetNodes()
                .Where(x => hexNodes.All(z => z.GetDistance(x) > 3) && CanPlaceObstacle(obstacle, x))
                .OrderBy(x => UnityEngine.Random.Range(0.0f, 1.0f))
                .FirstOrDefault();

            return node;
        }

eager fulcrum
#

oooooh

leaden ice
#

The parameter to SoawnObstacles

eager fulcrum
#
public class BattleGridObstacleDictionary : ScriptableObject
    {
        [SerializeField] private List<BattleGridObstacleData> obstacleList;
        [SerializeField] private int minObstaclesToSpawn;
        [SerializeField] private int maxObstaclesToSpawn;

        public List<BattleGridObstacleData> GetRandomObstaclesToSpawn()
        {
            var obstacles = new List<BattleGridObstacleData>();
            var numberToSpawn = Random.Range(minObstaclesToSpawn, maxObstaclesToSpawn + 1);

            for (var i = 0; i < numberToSpawn; i++)
            {
                var obstacle = obstacleList.OrderBy(x => Guid.NewGuid()).FirstOrDefault(x => x != null);
                obstacles.Add(obstacle);
            }

            return obstacles;
        }
    }
#

I forgot about that

#

can I set initstate in scriptableobjects?

leaden ice
#

Your brackets aren't matching

tough hinge
#

hello have anybody first person code

leaden ice
#

Look at StateHandler.

Fix your formatting etc

solemn raven
#

hi ,
correct me if Im wrong , but there was a way to allow users to change items on a list of a "CustomClass" on the editor
for example
public List<CustomClass> customList = new List<CustomClass>();

    using UnityEngine;
    using UnityEngine.UI;
    using TMPro;

public class CustomClass: MonoBehaviour
{
    public Image someImage;
    public TextMeshProUGUI someText;
    public Color someColor;
}

is it possible to be able to change the values of items on customList on the editor like the value of someImage or someText or someColor ?

leaden ice
#

Every { needs a }

#

You don't have that

leaden ice
#

Make it not a MonoBehaviour and add [System.Serializable]

solemn raven