#archived-code-general
1 messages · Page 55 of 1
@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!
it sounds like you are doing this
class Pool : MonoBehaviour {
public GameObject projectile;
public List<GameObject> pooled;
void Start() {
for (...) {
var go = Instantiate(projectile);
var bullet = go.GetChild(0).GetComponent<Rigidbody>();
pooled.Add(go);
...
}
}
}
this is wrong
do this
ayeee nice gg :D
I'm using the 3D starter scene and have added Network Object, Client Network Transform and Client Network Animator components to the players
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?
the host can move just fine and the clients can see it, but the clients are refusing to move at all
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.
you are at the start of a long journey
yes ty! I need to use the projectile class to handle physics impulses so a little rework is required but this is sooooo much better computationally. ty!
@worthy brook did you build this terrain?
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?
Depends. What's the pattern thereafter?
it's part of the template, I have another one, just haven't imported the assets for it yet
i think its the 3rd person controller asset from unity
or 1st person
okay i got you
yes it is the 3rd person template
basically a PvP isometric fighting game in an arena
😨
A script with mouse input detection and an array of actions could allow you to process different actions - possibly iteratively.
have you looked at the more mountains top down engine asset?
is this a game played with a controller?
it could be played with both M/KB and a controller
2021.3.5f1
haven't heard of it before
did you start with an official sample or template?
meta itself uses 2020.3.18f1
Sample? You mean the 3D project template?
no
you can take a look at this
this is a complete example
do you have a Quest or a Quest 2?
Q2
this stuff can be really really hard
they also support 2021.3.16f1 in https://github.com/oculus-samples/Unity-SharedSpaces
you sort of have to start with exactly one of their working projects
because there is a lot of nuance
So the random hangups and material crashes happen because of my unity version?
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
?!
but the punchline is, the only definitive way to diagnose issues like this is via git bisecting
How'd i do that?
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!
nope to using git?
yep
i have plastic SCM tho!
okay
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!
._.""
CharacterController only moving on the X axis?
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
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
It's using DontDestroyOnLoad so we aren't destroying between scenes
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?
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;
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?
are you using networked position synchronization
I have a ClientNetworkTransform on the object that's syncing everything checked, default thresholds, localspace off, interpolate on.
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
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.
How would I go about deleting a specific polygon from a mesh? In this case it'd be basic unity plane.
would it be possible for you to show the main code youre using for networking?
Do you want to remove polygon from plane or plane from any mesh?
You can delete a specific polygon from a mesh in Unity by accessing the mesh's vertices, triangles, and normals, modifying them, and then assigning them back to the mesh
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
and you want to remove the polygon completely?
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
so you want to use an LOD basically?
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
oh yeah ive seen that
But also for a plane instead of a cube sphere
can you make a thread
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);
To make the instantiated object a child of the game object this script is attached to, you can pass the game object's transform as the parent parameter in the Instantiate method
Hey guys, I was wondering if someone could help me determine why this method of turning a player to the mouseposition doesn't work?
what would that syntax be
I think its something wrong on the 21th line of the code it seems
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);
? But I didn't even send it yet
Thats best guess I had cuz you didnt
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
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
Why does it need a nearclip plane to function properly?
Also when is it preferred to use the raycasthit instead of the screentoworldposition
did you read the description?
I know that it gives the default 0 position
the third is the distance from the camera
Im unable to change any of the variables in the inspector of my struct
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"
oh sry
are they serialized and is the struct serialized and a field of a MonoBehaviour?
I was having trouble understanding why the distance from camera mattered
Yup
show relevant code
You mean the Slot list isnt visible in the inspector?
No no I can't change any of the variables in the inspector
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
Like I cant turn the bools on and off
Or change the gameobject some of the options are set to
U want Serlizefield not serializable.
[SerializeField] goes on a field. RestrictSlot is a type so it takes [Serializable] like you have
Finally Im right on something
Can you screenshot the inspector?
okay so the issue isn't that they don't show up in the inspector, you just can't change them?
Yea
are you perhaps doing anything to the list in OnValidate?
Thought it was a field he had not put in yet under or next to it.
wdym
oh
I see
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
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
!cs
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);
I'm trying to make the player look at the mouse position, but for some reason the screentoworldpoint seem to be very far away? It turns very slightly every time I move the mouse
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
then change the z position of the vector returned by the screentoworld
do you mean z in unity or the z-axis like math
z coordinate
Because if you meant the latter I already have, so that the player doesn't look up instead
z position
What should I change it to?
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"
this is 3d and the camera has a rotation on x
Could I have some help once you're done with him Boxfriend?
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
no, i clearly linked to the Alternate methods section
??? Am I not supposed to use screentoworldpoint then, I'm confused
scroll down to the Alternate methods section
Idk whats up with this
can't modify a collection while foreach'ing over it
oh shit
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?
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
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 😆
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
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
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
The Tile class will also contain the functionality on how the Tile should behave. SOs are just data containers that will populate your variables inside of your Tile class, so basically you'll only ever need to read from it once.
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.
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
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
oh yeah about that
could be easily done with an enum for each tile that corresponds to a database when asking for retrieval
Ill look into that method as well since it sounds pretty straightforward, so thanks to you also!
for chunk data I would store a 2d array of bytes where each byte is a block ID as in an index in an array of blocks. Then have an array of blocks where each block is a scriptable object which holds properties about the block such as name, texture, durability and such
this is more or less what I was describing
this?
yeah, exactly that 😄
thanks so much
Does anyone know if Oculus's eyetracking has a method to detect if eyes are closed or significantly off measurements for coding purposes?
Hey can someone help me wrangle this script? I can't quite get it to do what I want, running into weird issues and not sure which methods to use in some places
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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
does anyone here know how to deal with making a custom asset package?
is this a scripting question?
what other place should i ask?
I'm not quite sure what you're trying to accomplish, so I dont really know
hum well i am trying to make an asset package, issue is that Editor scripts are getting picked up but none of my "runtime" scripts are
i dont think there is another chat for this...
Are you using assembly definitions?
the asmdef files?
Yes . . .
Make sure you setup the assembly references in the asmdef files . . .
nevermind, I fixed it!
right, i fixed something and now i will try and look into that
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);
}
could use an interface i think or inheritance
oh I fixed it thanks
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
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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?
is BuildListOfSaveGameObjects() being called? The first line seems to clear the dict. SO data should persist through edit to run mode
https://docs.unity3d.com/Manual/script-Serialization.html Apparently unity cant serialize dictionaries. I don’t know enough about SO’s to know how that plays into things but that might be something to know about (apparently there is a way to serialize a dict in the custom serialization part)
Yea, the whole method itself is working as intended... and I was having this issue before I even added the .Clear() line
I just added that for some redundancy... because something else is clearing the dictionary.... I'll need that clear line once I solve this issue
I am also aware of this, I'm not trying to serialize the dictionary (although, I can if I want to, I wrote some code that does it by splitting the dictionary into lists and doing some inspector GUI magic)
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.");
}
}
}```
Dictionaries are not serialized by Unity, so entering playmode will reset the value to default
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
Correct, but you can use SerializableDictionary (3rd party) for example
Also a valid option
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 ;;
Hey not everything has to be super generic
but I like modular code systems u_u
But yeah if you can conveniently store it in a list and construct it at runtime its fine too
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?
In WebGL or what?
In WebGL you can use this: https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html
If it's not WebGL you'd have to use something like this:
https://github.com/sebastienros/jint
Probably easier to just find a C# Library instead or port the JS lib to C#
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?
Basically the idea is you include your js Library on your web page and interact with it from C# through the stuff in the link above
Ah so I'd need to add that to my TemplateData then?
Yes!
yo, this worked out~
You can bind C# function calls to JS too
guess it was just cause dictionaries and scriptable objects dont mix
Generally speaking if you're using require()/import() and so on you'll want to run a bundler like webpack to output your JS project
Then assign some globally accessible API to window
Then you can just call those functions via C#
Thanks for the help guys! this has definitely given me some extra resources to play around with ❤️
There's a guide in the unity docs, I've done it once
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
Makes sense
But if you just want a few helpers just follow that guide and it will work
ah doing some crypto shit
I apologise
I'm a blockchain developer and playing around with POW and creating gasless TX
Thanks Rhys that clarifies and helps a lot! I'll jump onto that now.
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();
}
lists are reliably ordered, right?
yes
They're just an array internally
I'm working on future proofing my save game system for my metroidvania, and oh man its beena task
future proofing is the enemy of progress
almost done though, and then I'll be able to add and move around save locations without breaking saves from previous game versions!
how can i make a sprite fade out?
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...
thanks
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
Maybe it cant compile UI package because of the error? Try fixing that first.
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
Wait you said it popped up after you updated, but was also there before?
What do you mean?
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
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?
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
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.
so i told you how i got the error i havent done anything frokm that
.
And this is my follow up question to that
there is no update for it
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.
Psd first
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
ok give me a second. I'm going to hop on my computer
take your time if you want we can vc too up to you it doesnt matter to me
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
Are collision normals oriented relative to the world or relative to the collider's transform?
When exactly did this error pop up? Is this a new project?
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
how can i tell and how new is new lol
idk if that helps
i think around there
This is your issue https://answers.unity.com/questions/1878657/textureplatformsettingshelper-does-not-contain-a-d.html first thing that popped up when I googled your error
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
Unity answers bug
yeah it’s probably a migration error or something. hi’s got replaced with that
kk
wait
it saying to delete psd
doesnt that delete my animations'
cause its a dependfencie
dependency
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.
ill try upgrading ig
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
version ocntroll?
git
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
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?
nice, glad you figured it out
no we still on ui problem
lol
anyone know what the package is for ui
idk if its this one
its that one
yes, seems like a bug. Restart Unity?
delete Library folder
it's Unity generated files. would force it to generate again. And get it right this time.
you could try Library/PackageCache first
try PackageCache first. It'll be faster and you can always go for the full folder after
Library/PackageCache
wait
ScriptableObjects will allow you to make a bunch of spells on the inspector if that's what you're asking. If what you mean instead is how to save the data you've entered during runtime, then you will have to serialize it between sessions.
yes, Library/PackageCache
k
i have spell prefabs already, but when instantiating them, i want to pick from a pool of possible spells and im thinking id need a text file or something to get that data
reopen when done?
and set the spell prefab's data to that spell data
You can make a temporary database that exists only at runtime
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
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.
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?
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
if you go with text file, json files can be a good option. Don't worry about encrypting unless there is a legit security concern (like online gameplay)
ah kk
how do i write a json file manually?
but can I have it snap to the sides?
I wouldn't write them "manually", use json serialization to serialize your data, and deserialize back to objects when you read it back
okay but then id have to have the data in a script right?
so that defeats the point doesnt it?
you want to make edits just free-hand rather than in your code?
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
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
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.
and really, json is overkill. SerializedObject is perfect for this
or a db if you're comfortable with that
yeah it'll be predefined
basically, if its predefined: probably scriptable object
if its not predefined: database or file
ahh kk ill look into scriptable object
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
Well, what is being null?
its not null but still giving me this error
i tested it out in Debug.Log();
objects[10].GetComponent<HoverUI>().Show(
objects[10].GetComponent<RectTransform>().anchoredPosition = (Vector2)Input.mousePosition+objects[10].GetComponent<RectTransform>().sizeDelta/2; is working
So it's either objects[10] being null, missing a HoverUI component or one of the things in the arguments being null.
ok
Debug each of them before that line and see what's null
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
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?
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
}
}
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.
i update the code, its strange
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
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
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
there's a million tutorials on how to make your character sprint, dont try and get it spoon fed youll literally hit a wall
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.
❤️ Thanks a ton
Everything is going great after I figured out that whole issue
It depends on how you have set up your animation events and how you are changing the variables through code
its good to have that one problem every once in a while, you'll enjoy it more after you figure it out
Yes, UnityEngine.AnimationCurve uses a cubic Hermite spline to interpolate between keyframes the Hermite spline is defined by the position and slope (or tangent) of each keyframe, and the curve is constructed by smoothly interpolating between adjacent keyframes. (hopefully im not too late lol)
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.
the docs would be a good start to learn about multiplayer code
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.
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.
its done @civic fern look my screen
but I will try again to import it!
because the fact that it works on the editor I find it weird
hm
You sound a lot like ChatGPT
Mhh nah why?
I wasn't talking to you
chatgpt is rather a beginner, you should not use it 
maybe i can reimport the assets lets try
@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
have u tried adding the assembly to your webgl build settings manually?
in player settings ?
coz i can't build rn
WEBSOCKET_SHARP ?
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.
Take a screenshot of the dll inspector
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?
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();
}
}
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
how would i rotate it with quaternions
do i use Quaternion.AngleAxis
you can, or Quaternion.Euler
this?
transform.localRotation = Quaternion.Euler((transform.localEulerAngles.x + xDirIncrement) * Time.deltaTime, 0, 0);
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
ok
so replace localEularAngles with localRotation?
or store the euler angle vector once and then never read from the transform again
imanager would be a good solution
another solution could be to use a messaging system such as the Observer pattern u can decide which works best for you though
Is there an easy way to check the length of a cross section of a 2D collider?
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!
(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
• !cdisc
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
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
okay ty
i know some people will be eager to answer my question here, so ill just leave it up here
Any advanced Rider user?
How to make it ignore PackageCache folders for code analysis? So annoyed it scans literally all packages
inheriting from a base class can be a good alternative approach, it a valid solution
how i can make the player not move on Y?
this is what i found online
Navigate to "Editor" > "Inspections" > "Code Analysis".
In the "Exclude files and folders" section, click on the "Configure patterns" button.
Click on the "+" button to add a new pattern.
Enter "/PackageCache/" as the pattern to exclude.
Click "OK" to save the pattern.```
where can i find a good tut about swarm pathfinding algorithms
Thanks the Observer patten seems handy too for the future
no worries, glhf :D
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
turns out variables you change directly through animations cant be changed (I think), but animation events function as normal code
confused me a lot but I think I figured it out for now
sorry for the ping lol basically just wanted to say thanks because that did set me on the path to figure that out
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
Does the error also appear in your Unity Console?
yes
Ah, your own class is named Animator, it's picking up that one instead of Unity's
alirght il try it out thanks
Refers to the class itself
thanks bro
Anyone can help me?
with what?
You need to ask a question in order to get answers
Where I can share Screen
on discord?
I want to share screen
Nowhere, you can record and post a video of it here
do you mean like screenshot?
Voice channels are disabled for obvious moderation reasons
And When I click Space
Please follow the !code posting guidelines
📃 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.
how i can make the player not move on Y
Presumably, the bullet "collides" with the gun, which runs OnTriggerEnter, and the thing you triggered with (the gun) gets destroyed, as per line 52
How can I fix that
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
No no, I really appreciate the response. Thank you for getting back to me 😊 I'm working on a curve fitting algorithm to reduce the number of keyframes in a source animation file and the math is pretty wild!
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.
thx alot🫡
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;
}
}```
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;
}```
No? Log to check if your if statement is running. The previous code you showed.
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
Skill-based jumping
You do not have the log inside the if statement.
i dont get it isGround should return to true and activate ability to jump again.
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.
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
{
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = true;
Debug.Log("isGrounded is: " + isGrounded);
}
}```
i logged it i receive nothing
Well, there you go.
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
{
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
anyone know how to create a dropdown in the inspector? rigidbody for example:
that isnt a dropdown
what is it then
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)
ok thx
pretty sure it's a toggle
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!!
SceneManager.GetActiveScene().buildIndex + 0
what scene do you think this will point to?
the 0th scene
that is true only if you are currently on the scene at index 0.
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
did you make sure to save? and have you considered adding a Debug.Log message to make sure the method is actually being called?
let me actually log it yeah
it doesnt even log it
when i click the button
that means the button isnt even triggering
do you have an event system in the scene?
i do
during play mode it has a preview you can view to see what is being clicked on
yeah
when i click on the button like that it converts eligibleToClick true
but like its true everytime i click the scene anyways
are you actually looking at the preview or are you looking at the properties on the event system? because i'm referring to this
and you see that the button is appearing in there when you click on it?
well nothing shows beside the selected:
its just that the eligibleForClick turns true
thats the only change when i click it
is the button actually interactible?
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
let me check the raycast target i might not actually checked that
okay it isnt a raycast target
okay so is the button interactable
well that probably should be. the text shouldn't be
i did create a button object n all, how do i confirm if its interactive tho, cuz like i did these same things for my mainmenu scene and its working perfectly
look at the button component?
lemme
but again, your image probably needs to be a raycast target since that is what you are clicking on
i tried that too
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?
didnt work
well you still haven't confirmed if the button is actually interactable or not. but at this point you should ask for help in #📲┃ui-ux since it is not a code issue
okay so not a code issue, right thanks!
ill ask there
and yes the button is interactable
Can I reuse an OnDrawGizmosSelected() from an object in a CustomEditor of a different class?
You could store the heat map in a (global ?) shader texture property, make a custom Decal shader and read that texture from within the shader using world space coordinates.
make the function that draws things public then call it from both places
e.g. make a public void DrawMe() and call it in both gizmo methods
Alright, thanks
It seems that I can't use Gizmo drawing functions outside OnDrawGizmos(Selected)
sure you can
as long as you're calling your function from one of those methods
Like this?
Editor scripts don't inherit OnDrawGizmos
I thought you wanted to do it from another script's OnDrawGizmos
then no you can't use Gizmos there. You have to use https://docs.unity3d.com/ScriptReference/Handles.html in editor scripts
actually yeah I can do that
lol
not in the editor script but the base script
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
The error is at
Collected[] collected = JsonUtility.FromJson<Collected[]>(webRequest.downloadHandler.text);
I don't think you can de/serialize an array like that with JsonUtility.
That's what I find online, but the first three snippets work
JsonUtility does not support a collection as the root object. it has to be part of some other object (like a class or struct)
This one does not give an error though
https://paste.ofcode.org/TyBPAeTMeqsLrgXgXscHTV
how come?
What snippets?
Where do you deserialize it?
webrequest and deserialize
https://paste.ofcode.org/wHzJxY3WcUNHr2WUjBkg3r
these three work
Are you sure?
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);
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
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
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
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
}
}
I tried to give it to chatGPT and it gave something similar, but it didn't seem to fully work
I can paste thaqt if you want
no, i will not help you fix code that was AI generated
Ok
How to type OR in Unity
||
there are beginner level C# courses pinned in #💻┃code-beginner , you should consider completing them so you don't have to ask basic questions like that
sounds like you're doing it wrong
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?
i'm guessing you didn't google it, because i'm pretty sure this video goes over exactly that https://www.youtube.com/watch?v=Z1qT65GL-6Q
A little confused on what you mean by "get the direction". Is this a vector2 or an angle?
a vector2. direction is just (endPosition - startPosition)
Ok
that dosent work for android build
then maybe consider mentioning that as a requirement next time
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
do you know how to tho ?
nvm i switched to grid layout
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);
}
i'm guessing you probably overwrite velocity immediately on the object
Here's the movement code for the player, which is what I'm using to test
https://pastebin.com/tA3L68bg
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
What is this supposed to be:cs Vector2 direction = rb.transform.position - transform.position;
Is the rb on a different object?
It's from this message
Oh are those meant to be reversed?
no, that's correct
Probably not. I was just missing context
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
I don't really see where, I never set it to a specific number anywhere, I always just add or subtract things from it
On that note, could you explain what this does?cs if (rigidbody2D.velocity.y < -20.4f) { rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x, rigidbody2D.velocity.y - 0.4f); }
Slows down player if they are above terminal velocity
but I wrote it wrong
now that i look at it
Yeah I see youre limiting the velocity but that one's wrong
Just needs to be + instead of -
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
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
k
please
Any idea why my sprite is spinning while the box collider isnt when I add torque?
rigidbody.AddTorque(impulse, ForceMode2D.Impulse);
The error points to line 74. Something you are using on that line is null.
i have initialized everything on that line
i am following this tutorial https://www.youtube.com/watch?v=MAAxL6Q_ElE&list=PL6PsTmPNvw0eZirNDjO8dL0Y6X0ZFGaMt&index=1
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...
Are you sure you don't have duplicate objects with this script?
nope
Does the object you assigned this script to have a rigidbody component?
yes
The error is telling you are wrong.
Nope as in you are sure or not sure?
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
I was thinking the basic search field on top of your hierarchy but I guess that works too.
Did you put the log before the error?
It needs to be before. If you get an error, that line is never reached
Those quotes look messed up
the start method is befor the other method
This is how it's supposed to look like, not sure why it's so messed up for him
Try manually retyping the quotes
If this log is in Start and it doesn't print... Then you have another error in Start
is the default physics engine deterministic now or not ? Conflicting information online
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
Actually, you can literally see the error in this screenshot..
I fixed the issue where it wasn't being pushed much, but now it only pushes to the left
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
the weird quotes is from the plugin in unity, in vscode its normal
Alright but fix the error in your Start method
what error
The top/first error in this screenshot
^
ohhhhh
its something todo with assigning the fov because as soon as i comented the line that sets the base fov, everything works
You most likely haven't assigned normalCam
i changed something in the camera earlier
Also you don't have to guess. Just double click the error, or look at which line number the error says
Noyce. Next time remember to look at the first error you get
Using the following code, I get a nullref error on ln72. Ideas? https://paste.hep.gg/esiwe.cs I've already tried changing the order...
Looks like platformInterface is null
platformInterface is null.
You should initialize it in Start not in a field initializer
Yeah was about to ask about that field initializer..
How can I go about Instantiating a cube prefab right next to another one? Same question about on top, below or behind, thanks!
Add an offset to the coordinates you put into Instantiate
Get that offset with the other object's transform.up/right/forward
Multiply with -1 to get down/left/back
Wouldn't it be position rather than transform?
as long as the cubes are scaled by 1,1,1 then osmal’s method works
hmm, so 2, 2, 2, no good?
you can do cubePosition + Vector3.up * 2 for that
so * cubeScale
Can you run a coroutine in a for loop?
what are you trying to do?
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
show the code
Ok
Give me a couple
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
let me also send a pic of the console
its starting at random values and then going down to 0
Hey guys i have a problem with my animation where it plays in the direction i animated it in. and in game the bread face towards the player so i need to play the animation towards the player.
nested for loops? where is i defined?
yield return
You cannot yield as it returns void
ohhh, is there a way to recreate the waitforseconds effect
maybe you can start a coroutine and perform setbool(false)
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?
can you share more or all of the script? there’s not enough information
ok
I'll rename it cause it's another solution at this point
actually im kinda busy rn so I'll continue this discussion later, sorry
could be. Can you share how you’re instantiating it?
Is it spawning it too low?
the transform of your gameObject's parent affect the transform of spawned object
ah, didn’t know that
Yeah, 0.5 instead of 1.
But when you look at the position numbers in console (not inspector) it is 1 somehow.
Hey, is there any way to use oncontrollercolliderhit() as oncollisionexit()?
Ohh... That's probably cause the scale of the parent is 2x?
Damn..
Thanks
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
Any idea why the parts are spinning like crazy?
Im just adding force to rigidbodies with circle colliders...
Try with a higher angularDrag on the rigidbodies
i have that set to 1000 for testing
In that gif?
Are the rigidbodies a child of anything, or is there any other script that could rotate them?
What if you try with a normal friction value like 0, 0.5 or 1
with 0 they dont spin but slide.
with 1 they spin
they are child of something but its just an empty gameobject with nothing attached
And with 0.5?
My point being, 10k friction is probably causing some anomalies
Does the ground have some crazy friction number too?
Not sure what is going on then. I would start with lowering the crazy numbers like 1000 as angular drag
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
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
How is your weaponParent oriented?
I would start with checking that it's actually facing forward in the player's local space
I actually only turned them up to figure if thats whats causing it
same position as my camera, tried changing it to be the rotation that the gun needs to be but didnt work
? It's rotated -90 on the y axis
Or is that the thing you tried
ive changed it to multiple numbers, the gun is always facing the right of the player
Is it a child of the player?
Is any other script modifying the rotation/position of weaponParent?
Also show this but with the weaponParent selected and with local space gizmos
the look scrip changes the x rotation of the gun so the gun always loks up and down with u
Y rotation is horizontal rotation
Not vertical
That's probably where you are going wrong
y i mean like up and down
You want X angle to look up and down
Yeah I know what you want. But rotating around the Y axis will rotate it horizontally
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
i know
No need to edit the message afterwards... Now the whole thing just looks confusing
i said y because i read mouse y and went with that
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
aand also cause y pos is up and down
Yeah well you literally said Y rotation which normally means Y angle rotation.
that is correct, its the gun that is spawning weird place
i have no interest in your actual issue. multiplying mouse input by deltaTime is wrong though
The problem is probably that you are instantiating the gun directly as a child of the parent, but still using world space coords/rotations.
See: https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
Probably wanna use instantiateInWorldSpace or just give it zero values or no values at all
ok
Also I feel things might be connected this.
Basically the sprite spins without the collider spinning along. It spins the collider along if I make the object float.
But for some reason it doesnt "stop" rotating the rigidbody if it would be blocked by the collider...
The bones are the only pieces that use a box collider instead of a circly collider
What if you try to actually freeze the rigidbody's rotation with constraints? To see if its even the rb spinning
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
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
I noticed something else... If I dont give the rigidbody an initial rotation it doesnt spin anymore
hmm
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.
because GetAllUnoccupiedNeighbours is not working as you think, log the returned count and find out
How can I figure it out based on the count?
because a count > 0 will cause the stack overflow eventually
wut? Its entire purpose is to return count > 0
then why are you surprised it gives a stack overflow?
Because I think this
if (costs.ContainsKey(neighbour) && costs[neighbour] >= price + 1) continue;```
must prevent the overflow
maybe, but have you actually checked it does?
As much as I can figure out from exceptions, it doesn't
But why...
It's the question
it's your code, not mine, debug the values rather than just assuming and guessing
@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.
I am supposed to recalculate it if I find a shorter route to it. That's the logic you can see in the condition
I dont know,
your current situation is you are getting a stack overflow
the only way you are getting a stack overflow if because CalculateCost is being called too many times recursively
So you need to figure out why that is, debugging the code will tell you this. QED
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?
10 to be precise. But after debugging I see that "price" variable goes over 50
Logically, it can't be over 50
I mean mustn't be
I can somewhat believe 20, but not 50
Hey
I have a weird problem with randomness
screenshots from 2 clients
both obstacles and units are placed randomly
My recommendation is to not use recursion at all 😉
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;
}
kind of a pre-req for A* though yeah nvm agreed
I do InitState() again in the script that spawns obstacles
Nope. Recursion is never necessary
Use a Stack
Or Queue
and for some reason Random.Range for spawning units works the same on both clients
but random.range is different for obstacles
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;
}
Not this
obstacles
oooooh
The parameter to SoawnObstacles
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?
Your brackets aren't matching
hello have anybody first person code
Look at StateHandler.
Fix your formatting etc
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 ?
Are you meaning for that to be a Monobehaviour?
Make it not a MonoBehaviour and add [System.Serializable]
Yup that was it , thanks ❤️