#archived-code-general
1 messages · Page 388 of 1
Its just the scene loading things for now , problem occurs in code here
You'll need to provide some more details on the actual issue and how you're confirming it.
Would anyone have a suggestion on how to do this better?
I wanted to create "fishing pools" on the fly depending on how many json files there in a folder and that works great!
Downside is that unity cannot serialize a dict so I created a list and have each one of these pools registering it's self on it.
However, I don't feel like this is the greatest idea as I think it essentially doubles the memory used by each pool (if I am right).
Anyone else have a better idea?
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's the string name consist of? The name of the pooling as the key? Why not just stick that in the FishingPool data struct then instantiated a dictionary using that value
You could just choose not to use Unity serialization and instead use proper Json serializer
I believe I missed a bit of context, I just want to serialize it so I can view it in the unity editor it's self. I don't actually have a need to write to a fishing pool here
Don't use dictionaries, use structs then initialize the dictionaires in Start()
how hard is it to allow render textures to render through other render textures?
Render textures are just textures. They can be rendered as part of many things(different renderers or ui objects), so your question without any context doesn't make sense.
I have portals I made using render textures and when I look at one render texture through another one it is completely black
see they're like black for some reason
Is anyone able to help me with why my agent in mlagents isn't moving? I dont think it's a problem with the AI related part of the code. I don't have any errors but it doesn't move.
This is likely due to the timing of when the render texture is captured(rendered to). It's rendered to before the portal renders.
Here's one thing to try to confirm if that's the cause: set the clearing flags on the camera(that renders to the render texture), to not clear.
- Share !code properly
- I don't see you moving it in your code.
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
sorry. I'll use one of those links next time. But I should clarify I meant to be able to control it with wasd, not have it just move using the code
I mean, you're not doing anything in your code for it to be able to move with wasd.
the // convert keyboard inputs to movement and turning
that doesn't do anything?
this is source code from a tutorial on unity learn so I don't really understand why it doesn't work
Then you're probably missing some more code. Double check the tutorial.
You're only querying the input. Not applying it anywhere. Not changing the position of the object or adding forces/setting velocity.
How did you fix it?
I mean, what did you change in your code?
Ok, so make sure you share all the relevant code properly next time.
Because you probably omitted the part that I was talking about.
Hey guys im having some strange behaviour with rendertextures.
Basically, I have 2 seperate cameras rendering to 2 seperate rendertextures
then, in a loop, for each render texture the texture data is retrieved from the gpu with AsyncGPUReadback.RequestIntoNativeArray (small note, this problem occurs regardless of the amount of cameras/rendertextures, even if just one)
then for each one it loops over all the pixels and determines which one is the brightest, and displays that so i can see it.
The weird behaviour im experiencing, is that for some reason it only factors the brightness of some things into the value/result from the gpu (some things being the sun in my scene), and for some reason the game objects that are clearly also in the texture just dont count
in the pictures you'll see the value with a blank shot, the value with my sun (the moon) in the shot, and then the value with a very bright sphere that should count towards the brightness but just doesnt
I'm not sure why the value I'm reading from the GPU isn't consistent with what's rendered to the texture.
i think im just gonna display what im getting on the gpu directly onto another texture just to investigate
so when i write that data im reading back to a texture it also shows the white sphere
i deleted the sun for good measure
and it still just doesnt factor in
like, its the same data
welpp
what is the point of your for loop, it doesn't actually do anything
im logging the intensity wrong
i just figured it out
this is better
and works now
there was never a problem with the data
not a good way to calculate color intensity though
what would you suggest?
convert to HSL
Alright, I need someone enlightened in the ways of rendering:
Is there a sensible way of making something render on top of everything else (3D space), regardless of Z sorting and such, that doesn't use a second camera? The project is in URP.
I tried solving that by copying and modifying the preset PBR shader so that it renders during the Overlay pass, but that causes some transparency issues.
to get a bit more specific, underlining what I added to the basic shader:
Tags{"RenderType" = "Opaque" "RenderPipeline" = "UniversalPipeline" "UniversalMaterialType" = "Lit" "IgnoreProjector" = "True" "ShaderModel"="4.5" "Queue" = "Overlay"}
ZTest Always
You'll probably need to issue the rendering command with the lowest priority or modify the renderer or material priority if that's even possible currently.
Still a toddler in the rendering topics so that sounds beyond me at this moment. I did not even start reading through the details of what the rendering pipelines are about.
But lemme check something
May I ask, is this just some debugging code or are you going to have this in the game?
I don't remember if there is still a setting like that, but there was a material setting called sorting order or rendering order.
wouldn't that be the Queue property? it has a value range of 0 to 5000
Overlay is a constant that equates to 4000
but any values above 2500 are treated as transparent objects
which changes some rules about how rendering is handled
Yes, that.
so yeah, I'm way past that step 😁
And the result is not very good
Exhibit A:
player's equipment rendering under far away decals
funny bit? the decal has a render priority of 2000
so this interaction makes literally no sense
not a game and not anything anyone else will ever see
just something fun im messing around with
I'd start by looking at the frame debugger and seeing where in the queue does your object and the decal render. As well as possibly seeing if it's a depth buffer issue.
Deferred render pipeline usually renders all objects in several passes: depth - opaque - transparent. If your object doesn't render into the depth buffer, transparent objects like the decal would definitely render on top.
Btw, this kind of features(first person hands) are usually rendered by a separate camera to avoid all these issues.
Should be fine then. Just though there must be a lot faster ways with shaders and stuff
lmao yes, and I'm deliberately porting this from a double camera set up because our publisher really wants FSR implemented
and FSR in URP is hard limited to work with a single camera
Where do you have that info from?
the head developer of FSR3 for Unity asset
I mean, it still displays stuff on screen, but both looks bad and causes performance hitches
would be cool if I could just render both cameras to one texture and then FSR that thing, but that doesn't seem to be on the table
the set up only allows direct camera feed input
hi there, is there an official answer to loading large video files for VR/Android? im looking at videos >2GB because of high resolution (8k)
Would camera stacking not work?
👀
that sounds like it might work
let's try
the project is using deffered rendering instead of forward so that's out of the question 💀
I need a bit of help with direction for my career.
I want to be an intern level Unity game developer , what should I study/focus on, which minimum level for each skill should I reach , what should my learning path,projects be for the quickest result .
i really need an advice since my family gives me 4 months before I have to find work .
The most important thing when looking for a job without prior experience is the portfolio, so that's what I would focus on
That said the chances of getting a job in 4 months are very slim no matter what you do
I just need my levels to reach the required level
There are no levels in real life
Get a temporary job. Learn game dev in your spare time, it will take longer than 4 months
Then what should I focus on, what skills, knowledge should I get first ?
100% this
At the very best get a job that is fine with teaching programming
Learning proper programming is a big part of learning Unity so you can get experience in using C# in general or perhaps something similar
A lot of concepts apply in general
first, I don't know what a "level unity game developer" is. I assume you mean level designer? You want to design and build levels?
This is an art job. You'll need to learn all the 3d skills, but also the theories behind level layouts.. for as many different genres as possible
oh no.. I've split that up incorrectly.. you want to an intern job as a Unity Game Developer.. ignore the above
Make and finish at least three complete projects (project != game) for your portfolio.
Show an eagerness to learn and never stop learning.
Im working on it, but honestly I need a more structured learning path, right now Im just trying to learn how to remake games I have played and learn how to make things work. But it feels slow and I feel like I don't have a good direction.
I think I will get there eventually, but I want to do things more efficient, I really need some help with it.
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I tried Unity Learn, but they are too slow and I'm looking for a more hands-on aprroach as I like making my own projects
You are supposed to follow along in the pathways by making a project with them
if you want a job in programming, you must know these skills to impress the people who are hiring you, There are tons of guides and tutorials on unity and C# to help you do so
You can only learn so much from guides and tutorials like the link above, you must apply these new things into a couple projects, If these tutorials and courses are to slow for you, You would have to just start making projects so you can learn more, as for things you do not understand use the documentation (which will most of the time clear things up).
Yes, that's why Im looking for the minimum knowledge and skills required for an entry level job, and the direction to learn about them ( Such as how to use serialization, how to implement spawners or ways to refer to an object ,.... ) I only know some of which I have to learn, but my knowledge about them is very fragmented and I don't have a proper learning path for those who want to make a project. So I hope someone can help sharing a path/ document how to learn , what to do, what to make first for a more efficient and easy to understand path without having to use Unity Learn (honestly they should update that and uploads the video on youtube, it would help alot).
There is always google to learn specific skills that the pathways or beginner tutorials do not teach you, you can use documentation to learn pretty much anything in the API and engine you are unfamiliar about but have the basic understanding on what it is, you can always look up intermediate courses for unity and or Csharp as well, remember the !docs and google are your friends https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/, Also to add on, you should not be looking for the minimum knowledge for a job, you should be looking to strive and learn so you can impress the people who are hiring you so they pick you over other candidates, for if you only strive to be the minimum you will learn nothing but the minimum.
I have recently got multiple occasions when me and a collaborator receive merge conflicts when attempting to merge a feature branch to the main branch. And It happens usually because gameobjects are deleted or re added to scenes etc. What are some good conversations or good practice to make it less troublesome?
dont allow more than one person to work in a scene at the same time
Work in prefabs that you just put into the scene on your or his end (or at the start so you each have your workspace)
use multiple scenes
I'm encountering an issue where my particle system will play in the scene, and will activate in game mode when using play on awake, but it won't activate when I use the .Play function.
Does anyone have any suggestions?
This is a coding channel
I'm trying to activate it via code. What channel would be more appropriate if not this one?
Do .Play(true)
i assume you have child particles, that wont trigger without the true
Perhaps share your code in that case
emit sends out a defined amount of particles, ignores the emitter settings
Just tried this but it didn't have any effect.
the bool is just for withchildren
is the particle system disabled, or the object it is on?
Sure
public abstract class BattleMovementController : MonoBehaviour
{
protected Vector3 EndPoint;
public float MoveDist { get; set; } = 1;
public readonly float MoveCooldown = 0.2f; // Cooldown between movements
public readonly float MoveSpeed = .05f;
protected float LastMoveTime;
protected bool CanMove;
protected Coroutine MovementHelperCoroutine;
[SerializeField] protected ParticleSystem _moveDustTrail;
protected void Start()
{
Instantiate(_moveDustTrail, transform, false);
}
}
public class PlayerControllerBattle : BattleMovementController
{
protected override void TryMove(Vector2 direction, float moveSpeed = .05f)
{
Vector3 newPosition = new Vector3(TruncateFloat(transform.position.x + (direction.x * MoveDist)),
transform.position.y, TruncateFloat(transform.position.z + (direction.y * MoveDist)));
//Bounds must be withing designated player area;
if (!BattleStateMachine.Instance.BtlGridManager.GridBoundsPlayer.Contains(newPosition)) return;
CanMove = false;
EndPoint = newPosition;
if (direction.magnitude != 0)
{
Debug.Log("Particle system should be generated"):
_moveDustTrail.Play(true);
}
MovementHelperCoroutine = StartCoroutine(BattleMoveHelper(moveSpeed));
}
}
pls put the cs after the three back ticks.. so it's colour coded and readable
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
copy exactly as it is in that msg ☝️
The system is enabled and the object is on.
If I start game mode and press play the particles will be emitted.
move the _moveDustTrail.Play() to some where it gets called without any conditions infront of it
I've tested it by moving it to the line right after it's instantiated and I still don't see anything.
This is what I had to do in my asset
ParticleSystem.EmissionModule dustEmission = _moveDustTrail.emission;
smokeEmission.enabled = _shouldEmmit;
I'll try it
The issue was that I'm blind.
_moveDustTrail = Instantiate(_moveDustTrail, transform, false); //New```
I never had a reference to the instantiated particle system so I was just trying to play the
uninstantiated one, which caused the problem.
Thank you for your help everyone.
😄
i have been trying to remove grass from area of a instanced game object. i already lost hours on it, anyone have some idea how to grass from a radious around my gameobect in unity?
Ive been thinking about remaking my dialogue system in Unity 6, but i'm wondering if I should still use the graphview or move to something different like the new behavior package.
Graphview is cool but remember it is still Experimental so anything can change
the old GraphView is experimental too
its been a nightmare to deal with for the past few months due to the lack of support
Frankly im willing to dive into the new one due to the fact its going to be properly supported (although i probably wont swap yet because the first release of the game will probably still be Unity 5)
Not really coding related but i'm wondering if i can make a Mesh using a custom vertex layout, i want to use half2s for 2d positions, and remove normals and tangents. I assume I can set set vertex attributes somewhere, but i'm not entirely sure how
For an imported model or a mesh generated from script?
generated in a script
It's possible with the more recent MeshData API
https://docs.unity3d.com/ScriptReference/Mesh.AllocateWritableMeshData.html
Ill look into that, thank you
Why exactly I have this as part of my build data? Does the Lit.shader is a text file or it's the compiled version of it?
Those are all the compiled shader variants from that shader.
i have an rectTransform object with height set to canvas height but it's higher. y?
why am i getting the exact same error 6 fucking times
because it tried to access it 6 times?
What have you tried? And is it unity terrain grass?
its just creates a new error i try to run the game
Yes, it's happening each time
You need to fix it
how
read the error
Stop trying to access a component on the object that doesn't exist
and apply what it says to your script
did you assign the animation in the inspector
yes i think
You don't need to
You need to just not be doing that GetComponent
Or that component needs to actually exist
is Animation componenet still a thing
oh yeah my bad 😅
Is it actually enumerable? That's kind of weird
Don't guess, actually go look
I guess so
that looks like the documentation code 🤔
animation != animator
Okay what about the Animation component that you're getting in code? Show a screenshot of that one
this?
No, that's still an Animator
I'm guessing you took the code from the animation documentation here https://docs.unity3d.com/ScriptReference/Animation.html
but if you wish to use an animator, you should probably learn how to use it https://docs.unity3d.com/Manual/class-AnimatorController.html
unity is fucking alien software
No, it's english
the words "Animator" and "Animation" are not the same word
That is an Animation Clip
yes but there is like 15 things called animator
Which is neither an Animation or an Animator. They both use the clips
No, actually. They all have different names
There's Animators, Animations, and Animation Clips
So, if you want to reference this component, you should use this component's name
what component???
...the one in the screenshot
and what am i looking for
Is that the component you want to reference
yes
Then you would use that component's name for the thing you want to GetComponent
Instead of the name of a component that you do not have and are not trying to reference
like this?
Okay, do you have a component named pinable zombie
Okay let's go with that. Show it
should probably configure ide. How is there a whitespace in a class
are you talking about this
that is not a component
That is not a component
GetComponent gets components
Not asset files
anyway you should not be using the animation component as it is old and legacy, instead you should use the animator which is newer and recommended
I can tell that
So, get the component you actually want to reference
and change the animation state from there
also should probably be in #💻┃code-beginner
You should probably start by learning the basics of Unity scripting. Start here: 👇 !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
mostly im trying to remove a big chunk of grass based on hte center of a position, but the problem is that the point i set the removal of grass is counted as a edge
for some reason
ahh yess 对文档有任何疑问,请移步至开发者社区提问,我们将尽快为您解答
i use ff. maybe try reinstal
But if I only have one scene
well I have two, one for the menu
So when I create gameobjects, I create them in the prefab folder and drag them into the scene hierarchy.
Split the scene up into multiple
Hi, this is my first time writing here but I just don't know what to do atp.
I'm making a game for a college project. It generates a map out of a pool of prefabs. Each instantiated prefab has a DungeonEntrance that has a special material that will change color depending on the difficulty. For this I have three scripts IntersectionManager (generates the map), DungeonEntrancePreset (a scriptable object that holds a color, and a difficulty), and DungeonEntrance (generates a difficulty, and based on it, takes the correct preset and loads it to the material). All of this works fine, but I want to take the difficulty generation from DungeonEntrance to IntersectionManager, and it just won't load the preset for some reason.
1st image is the block of code in IntesrsectionManager that generates and assigns the difficulty to the street. Second and third is the DungeonEntrance code. Fourth is the DungeonEntrancePreset Scriptable Object.
please help
sorry, I f'd up with the images. Here's the one that is the block of code in IntesrsectionManager that generates and assigns the difficulty to the street.
I have a Scriptable Object that holds a prefab in an object pool.
I have a second S.O. that holds prefabs to clone and spawn.
I want this S.O. spawner to use the prefabs in the pool, rather than cloning them.
What is the best way to do this without nesting an S.O. inside of the another S.O.?
my text field looks like this. on first editing it all erases but after this it doesn't & i don't see the cursor. there's some code for this - the most that may interest - in update() i edit textfield & stopping doing it until in-game writing stops. i know, it's selecting, it doesn't seem to edit in game but it edit's in the editor window
!code - and it's also unclear what your actual question is.
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
sorry ): as I said first time here
I have a Scriptable Object that holds a prefab in an object pool.
What do you mean by this? The SO references an ObjectPool? And the contents of the pool are... prefabs? Or do you mean instances of prefabs?
I want this S.O. spawner to use the prefabs in the pool, rather than cloning them.
The second SO or the first one? And I assume you mean instances, not prefabs. But yeah that's kinda the whole idea of an object pool.
What is the best way to do this without nesting an S.O. inside of the another S.O.?
What do you mean by nesting exactly? You mean just referencing one from the other?
I want to attach scripts to projectiles at runtime, but im not sure how to get the script i attach at runtime to interact with the projectile its attached to. specifically, i am going to spawn in the projectile which will have a hitbox component, and after the projectile has been spawned in, attach a script to it (ill call it script X) and then when the projectile hits something, script X will run its code.
What's wrong with the usual ways (i.e. GetComponent etc)? But also - why attach it after spawning instead of just using a prefab?
when the projectile hits something, script X will run its code.
This is usually done via physics callbacks e.g. OnCollisionEnter
So, I have a isometric game with a that has a semi-procedural generated map, to generate the map, I have prefabs that are instantiated dynamically depending on the exits (like The Binding of Isaac does). Each of these prefabs (which are tilemaps) have nested a DungeonEntrance tilemap, which has a shader material and a script called DungeonEntrance (the one on the photos). And as child of that DungeonEntrance tilemap, there is a collider that has attached another tilemap with a tilemap collider and a composite collider, as well as an IEntractable trigger script whith OnEnter, OnInteract, and OnExit. So the idea is that at runtime, each street gets assigned a difficulty when they are instantiated, then the player walks on the collider, calls OnEnter (which has assigned in the inspector the TurnOnDungeonColor method on Dungeon Entrance) and changes the color of the material of the DungeonEntrance depending on the difficulty assigned (which is generated on the script of the last picture). These colors are decided by some scriptable objects presets I made (3rd image).
The problem is that everything works fine, until I walk in the collider and the debug.logerror that is in TurnOnDungeonColor method is displayed. But I don't know why is the _current preset null. Everything is correctly assigned on the inspector, I debugged all processes and none of them give errors.
I really hope this was more understandable.
sorry if that seemed like a newby question, im relatively new to unity. based on what i just read on getcomponent, if i attach a script X to my projectile, and when my projectile hits something, i can just call getcomponent<script X> and then call any methods in script X from the getcomponent call to apply to whatever I just hit (i.e. inside the onCollisionEnter method)?
also you might be right in that I don't necessarily need to attach it at runtime since for some reason I thought that objects could only have one script on at a time. I can just attach script X to it beforehand.
on prefabs, I will have to look into them to see if that is somethign that could be useful for my case.
also you might be right in that I don't necessarily need to attach it at runtime since for some reason I thought that objects could only have one script on at a time. I can just attach script X to it beforehand.
Objects can have any number of scripts you want
if i attach a script X to my projectile, and when my projectile hits something, i can just call getcomponent<script X> and then call any methods in script X from the getcomponent call to apply to whatever I just hit (i.e. inside the onCollisionEnter method)?
You call GetComponent on a GameObject or any component on that GameObject to get a component from that object.
You can also just call it directly in a MonoBehaviour and it will get a component from the same GameObject that script is attached to,
But yeah these questions are the bare basics of UInity, really you should be in #💻┃code-beginner if you're a beginner
yes i was thinking that after reading my response so i will move my questions to that channel
I don't see any Debug.LogError in the code you shared. But no that was a pretty convoluted explanation. Presumably if something is null it was either never assigned or it was assigned to null.
YOu can work backwards to find out
the debuglog.error is on the second image nearly at the end.
And that's the thing, I really don't know how to figure out what's failing.
I want to add that, I used to have the GetRandomDifficulty method on the DungeonEntrance script instead that of the IntersectionManager, and this way it worked just fine, and it's the exact same logic.
If you already have the script X on the projectile, you can just directly call the OncollisionEnter in script X (as long as script X is inherited from monobehaviour) and use that to detect if your projectile hit something, Also consider using a prefab for instantiation so you can avoid adding a script onto each bullet every time.
If you don't know, debug it. Find all the references of the variable and instances of assigning a value to it and debug the new value. Somewhere it would be null. That or if it's null from the very start, debug it in awake or start and see if it's null.
Basic debugging techniques should get you there
more logs and/or attaching the debugger
Also I would presume adding a script to the projectile using Addcomponent would be pretty expensive over time for every bullet, although I do not know how optimized it is since I never use it 🤷♂️
they arent going to be bullets but rather spells that the player casts but yeah i guess the sentiment would still be the same. I am doing some more research into prefabs and the getcomponent and am probably not going to add the script onto the projectile at runtime and instead add it once when the spell is created by the player in the craft menu
I debugged the processes can I share the screenshot?
I really need a hand here, but my problem involves some extensive coding. At one point the game was working, and when I tried to change something in my existing codes, the whole sprites and cards aspect of the game stopped working (I'm doing something akin to Reigns). I'm just wondering if I should post the entire thing here with links to break down the code, or not. Mainly because of it being an extensive problem, looking at three different codes.
Feel free to send screenshots if you think they are relevant.
Use code sharing sites if you are posting whole classes !code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
So, here are de debug logs, the only error showing is the one that was already in the code screenshots. I don't know how to solve this ):
I'm aware, yeah. I'm just debating on it because it's REALLY extensive, and I don't wanna be annoying with it, since it's three different scripts that could be wrong
Did you do what I suggested here:
#archived-code-general message
?
Debug on awake? yes, I just did, also initialized
Debug whenever the value of the variable is changed I mean.
When you expect it to not be null
Also, you still didn't share the code correctly, so I can't even confirm what we're debugging.
Worst case people ignore it or look through it and don't see any obvious issues. Debugging is a lot easier when you have the project open in front of you.
the easiest way to fix code that was originally working but is now broken is to back track and see what you changed that broke everything and find a way to fix it whilst getting the outcome you desire
https://paste.ofcode.org/iRyN2ehN3NMyd64NrRnRCd I put everything in a single pasteofcode, I don't know if that is ideal, I can separate it if it's any better
Also, I didn't put the whole IntersectionManager code because the only part of that code handling the difficulties is in that method, but I can put it there if neccessary.
Right. I'll get to work on it then, because I seriously don't know what went wrong
Setting few breakpoints and stepping through the code can reveal a lot of things.
I suppose. The issue is that I added things on three separate scripts to make something happen throughout the gameplay, so it might be a little tiring to go through them all
IDEs also can also breakpoint and log conditionally if it's highly interactive
So essentially, I wanted to make tweaks to my scripts to make an event system, in which some cards that showed up to the player had orbs atop them, with flames indicating the "number" of the event the player was in (Ranging from one to four). In the midst of that, the script would make a choice of swiping the card left or right, trigger the next event depending on the choice taken, causing the card to be "turned off" and not appear in the deck anymore, and make the next number of the event pop up instead.
But when trying to change the code accordingly, the sprites of the cards I've made became messed up, and the whole card system just went bollocks and refused to work anymore. Even further than that, replacing the code with the old one to attempt and mend the situation, didn't fix it at all, and the card system was still fucked up. Needless to say, I am TOTALLY lost as to what to do here.
These are the Card, CardDisplay, and GameManager scripts BEFORE I've done any changes.
And these are the Card, CardDisplay, and GameManager scripts AFTER the changes.
(All the links are safe, I just did it this way to make the chat less cluttered.)
There are several possible explanations:
- The object that the method is called on is not active, so awake or start were never called on it, thus, even if the preset is null, there wouldn't be a log about that.
- The method is called on a destroyed object that doesn't have valid values. This one is unlikely.
- The method is called on a prefab, in which case it's the same as 1.
Debugging the object that the preset is null would be the next step.
I am experiencing an issue with my radar script, the if statement inside the for loop seems to be going off twice, even though its only supposed to go off when the difference is under a certain value. https://hastebin.com/share/cabacuvequ.csharp https://streamable.com/11b59i
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I'm not sure what is causing this issue, as I believe the way I am calculating the angles is correct, but I could be wrong.
Anyone here has a good C# FSM library recommendation?
I'm looking at State Machine Compiler but it has its own domain language which is kind of annoying
how do i get dictionaries to appear in the editor?
you don't. they aren't serializable
or, well, you'd have to do it yourself
or maybe someone's already done it for you
but you can't do it through built-in means
you could use a list of structs with keys and values
and then process that into a dictionary on startup
I saw some people using the SerializedDictionary type
but i cant use it for some reason
ive seen it in vids
okay i found some assets on the asset store
but all of them are broken
im using unity 6
Whats the best way to code enemies? I know you can have basic movement script and then a different script for each individual movesets but if you have multiple instances of that enemy then whats best way so they dont override eachother?
there is no "best"
and an answer of what's a good way to do so will heavily depend on how you design the enemies and what kind of game you're making
Well I have a roguelike that has 4 different enemies atm 1 ranged, 3 melee with different movesets. Havent really progressed much since dont know how I should code it. Esp if there is multiple of them in one room and where they dont mess with each other
AI is kind of a big topic on its own as one enemy can have many techniques and algorithms used with it that are common in AI behaviour - for example if you want your AI to move around objects and avoid bumping into eachother you can look at "obstacle avoidance" or "flocking" AI algorithms, or you can try A* pathfinding or Unitys built-in NavMesh (which AFAIK is best for 3D and requires baking your map to identify what is "walkable" for your "agents") - if your AI only need to perform 1 set of logic at a time, you could look into a FSM (Finite State Machine), if they have complex cooperation logic, then maybe a Behaviour Tree, if they have other complex logic, maybe a GOAP system, theres lots and lots of ways to approach AI, and maybe you might need some parts or an entire implementation of a particular approach to AI - I would maybe start with looking into the different approaches with a search like "ai patterns in game development" or "ai patterns in unity", then try to plan out how your specific AI should work with the logic of one of those patterns
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Guys i have seen recently some issues with UnityAds that works on editor but it doesnt work on build. Im having the same problem and I tried to solve with many changes but nothing. Im using the same code of the documentation
not much we can do from here, start checking the runtime/player logs
The first SO references a pool in which the contents are a prefab, yeah
The second SO has a reference to a prefab which it then clones. I'm looking to have it use the first SO as a way to recycle assets.
I don't want to put one data container inside another, if possible. I'd like for the second SO to get the data from the first SO with a different method, but I don't know that that would be.
What do you mean by putting one inside the other. I don't understand that
I think you're probably just confused about how references work
The objectPool SO would be placed inside of a field in the objectSpawner SO
the objectSpawner SO is then placed inside a third object to run it
I don't think I should be storing data like that
I'm thinking I could combine the two SOs
I'll look into that first
Hello! I'm working on a 3D top down game and I'm stuck at implementing the melee attack functionality. What I essentially want is the player to stop moving on attack, turn to look at the mouse cursor in world space and trigger an overlap capsule check. The Activate method is called by the ability holder who is controlled by the player controller that uses the new input system (mouse left click).
The functionality I want: The player walks using WASD and rotates in the direction of movement but when attacking it will stop and turn to face the mouse position and damage whatever hits the capsule check. This is basically the control scheme of Hades if it helps you understand better.
Issue: Most of the times when I left click the player will rotate towards the mouse but will quickly snap back to the previous rotation. The attack direction is correctly calculated (I'm using a debug capsule function) but the player for some reason snaps back like the rotation never happened. I even disabled all of the scripts in case anything was interfering (including movement script).
The melee attack ability code: https://pastebin.com/BZ85378g
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 objectPool SO would be placed inside of a field in the objectSpawner SO
Again what does this mean exactly
if you mean:
class ObjectSpawnerSO : ScriptableObject {
public ObjectPoolSO pool;
}```
Then it is not "stored inside" or "nested".
It just means the spawner has a _reference_ to the obejct pool.
That's all
May I know what you're trying to achieve with the if code block?
it would seem I've had a misunderstanding of the situation
I overestimated it
Okay
Anyone worked with .sentis files? How do you generate them?
Edit: think I found how (https://docs.unity3d.com/Packages/com.unity.sentis@1.3/manual/serialize-a-model.html) - always a couple min after asking, even if searching for quite a while before, right? 😄 -- wish me luck ^.^'
I have two angles, one is the angle of the ray that's on the radar screen. The other angle is the angle formed between the Vector3.forward direction, and the direction the object is from the player. I am subtracting those two angles from eachother, saying that if the difference is less than a certain number, ping an icon onto the radar screen.
Hey I have an issue that I have been trying to fix for the last 4 hours and I am stressed and getting nowhere with it...
I have My player controls with an action called submit which is assigned key values to space and enter.
There is a lot going on but it is supposed to log some information when pressing these actions within a 2DCollider. I have added debug messages and it seems that the inputs are not being registered for whatever reason.
I dont want to spam this channel with a bunch of out of context code but I would really love some help on this as its been multiple hours and i am getting nowhere
the chances of an Input firing on exactly the same frame as a collision are very small indeed
its a static circle collider, but I know that the collider works as it console logs when the player is close and not close but whenever I press the action key nothing displays in the console log
public void SubmitPressed(InputAction.CallbackContext context)
{
if (context.started)
{
Debug.Log("SubmitPressed input detected");
GameEventsManager.instance.inputEvents.SubmitPressed();
}
}
try logging before the if, (Debugging 101)
This code here should output the bottom 3 lines in the console when the submit action is pressed. this isnt happening and no amount of debugging is detecting the Submit key is being pressed/Registered
private void SubmitPressed()
{
Debug.Log("SubmitPressed called");
if (!playerIsNear)
{
Debug.Log("Player is not near");
return;
}
Debug.Log("Starting quest: " + questId);
GameEventsManager.instance.questEvents.StartQuest(questId);
GameEventsManager.instance.questEvents.AdvanceQuest(questId);
GameEventsManager.instance.questEvents.FinishQuest(questId);
}
then your action is set up incorrectly or it is not enabled or you have not subscribed the method to it
Thats what i thought at first but I cant see whats wrong with it
is there a way i can show you or find out myself whats wrong with it because every other action works in my input action asset
Start adding more debug .logs
how do i reference objects from two different scenes playing at the same time to a singleton in DontDestroyOnLoad?
and how would i make these objects interact with it/use the references?
just use the singleton?
nope, every object just refuses to take the references due to the reference not existing, no matter what i try to set it to
for now, my latest try has a script that has an inspector reference to everything it needs in both scenes, instantiate the singleton in dontDestroyOnLoad, then pass those references to it, all in negative execution order
instantiating is the lowest order, then reference giving right after, then every other script
any ideas what could be wrong?
https://unity.huh.how/references/cross-scene-references
here check this
I see, even I am a little confused.
So what you're trying to achieve is that the object only gets pinged once per radar sweep? @dense estuary
Yes
The reason rayAngle uses -radar.transform.forward as the axis is because the radar is UI, rendered to a render texture, and displayed on an object.
Ah I understand now. So what you could do is to track if object has been pinged, then skip the object you've already pinged during the sweep, then clear the tracked object after the full sweep.
Hmm, that should work. One thing I've realized is that this script has gotten quite complicated, I'll probably rewrite it using rotating raycasts instead of a bunch of vector calculations.
However, I'm not sure how I can rotate a ray.
Oh, it seems you just multiply its direction by a quaternion.
yeah, and then just make it visible as long as theres contact?
Hi, what is the JobLength field used for when using Burst jobs? Is it just an indicator of complexity?
you're talking about the array length ?
its how many iterations it will run
i have already tried the second and third options, but the references are always empty anyway
you'd have to show the full setup, its difficult to say wat you did and didn't do
I'm follwing catlikecoding's tutorial on procedural meshes, and i mean the first parameter in ScheduleParallel job.ScheduleParallel(job.generator.JobLength, 1, dependency);
arrayLength The number of iterations to execute the for loop over.
https://docs.unity3d.com/ScriptReference/Unity.Jobs.IJobForExtensions.ScheduleParallel.html
one script instantiates the singleton and send it to DontDestroyOnLoad on awake, then i have a script on each scene with a setup like this:
[SerializeField] GameObject terrain
[SerializeField] GameObject player;
private void Awake()
{
MasterSingleton.Instance.KeycardsHUD.Terreno = terrain;
MasterSingleton.Instance.Player = player;
MasterSingleton.Instance.PlayerHealthHUD.HealthScript = player.GetComponent<PlayerHealth>();
}
to tell the Singleton its references, after that then every other script runs and tries to use the singleton
Ah so it foes more than just spawn a oncurrent thread to run the task on, ty
their default execution order is set to -5 and -3 respectively, and every other script is 0 or higher
you should reserve accessing the singleton in Start not Awake otherwise you get nullref
so what is the current problem? whats not working?
every scripts returns a object not set to instance of an object while trying to access it
it seems changing it to Start has at least reduced the amount of errors
hold on, i think i forgot a few
okay so , which ones are throwing nre now ?
nope, nevermind
the amount of errors reduced were due to the references being set at the start of awake, when it had a problem, everything else after awake would simply not happen and cause other problems
the problem is inherently the exact same
i just dont understand what is possibly wrong about all this
everywhere else says this should work fine, script makes singleton in DontDestroyOnLoad, scripts with references send them to Instance, then every other script just takes it from Instance if needed
or, the scripts themselves game themselves as the reference if it needed it
it should work, it MUST work, but it just doesnt
Indeed.
maybe share the scripts / setup ?
+screenshot errors
the reference-giving scripts are about the same as the one i've said prior
the errors are all NullReferenceObjections, in Awake, Start, Update, doesnt matter, if it tries to get anything from Instance, its null
ur logging Instance.player but where is that assigned before the log ?
a script in each scene with default execution order -3, with private serializefields of every reference needed of that scene which is assigned to the singleton like this:
private void Start()
{
MasterSingleton.Instance.CartoesHUD.Terreno = terrain;
MasterSingleton.Instance.Player = player;
MasterSingleton.Instance.VidaJogadorHUD.VidaScript = player.GetComponent<VidaJogador>();
}
i would show a pic, but there's a bunch of unrelated stuff there
the start script is just that though
you don't see the issue here though
if i did i wouldnt be posting it here
consequences of bad design and messing with execution order generally makes it worse
-4 means it runs before -3
Accessing Player in -4 before its assigned from -3
i dont see the problem? i create the script first (-5), i load it and check if there is another singleton (-4), and then i assign the references (-3)
everything else is in 0 or higher
Instance.Player in that log would for example throw null because you don't assign Player until AFTER you run that line
so far thats the only null reference I can see since thats all you shared
oh right, the debug.log, that is just a test a did earlier and i forgot to remove
I mean..this is why i requested the most recent null logs and their line number + associated script
its a singleton, if i had to share every object that tries to get a reference we'd be here for a while
otherwise not sure how anyone can help here
i'll show the error log tho
can give you general help ig, just ensuring the correct order since it seems thats not the case here
wait, now that you pointed it out
mess with the order of execution on specific scripts if its absolutely necessary (maybe a bootsrapper object)
that debug.log only happens after every other object's Awake
can someone help me with a problem with my level system?
i gotta delay everything until after the singleton is awoke, seems like more scene shenanigans
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
Who doesn't love magic numbers in script execution order
Only a matter of time until we get to 9999 (IMPORTANT: don't change this, this has to run last!!!)
So, I am attempting to do this using a dictionary, but I've never used dictionaries like this before. https://hastebin.com/share/evefuserof.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
In the start method I am trying to add one key for every icon. But it seems to be throwing an error when I try to add.
wait, I think I fixed it
alright, i ditched the singleton instantiator and just put it directly in the scene that will stay for most if not all of the game (its still being put on DDOL tho), now it is without a shadow of a doubt the first one to run and FINALLY be loaded before the other scripts try to set its references
Anyone have idea why my test returns color that has 2 in red, 1.3 in blue??
every error is gone now
show code
cant show code really because its test for a tool which handles tweening in background but
it adds color
new Color(1, 0, 1, 1)
to the color
new Color(1, 0.2, 0.3)
Presumably your code is creating such a color.
How is that a shock then
well why it can go over 1?
Because numbers can go over 1?
But also because it's just a number
really thought colors are clamped in background
So I'm using Unity's character controller package and unfortunately the slope logic on it is arse, so I'm trying to resolve the issue of having a bumpy downward slope velocity.
_controller.Move(inputDirection.normalized * (_speed * Time.deltaTime) + new Vector3(0.0f, _verticalVelocity, 0.0f) * Time.deltaTime);
This is the typical movement call and I'm trying to figure out how to go about blending the input direction to that of the slope direction that's given from doing a cross product from below the player.
Rather, I'm not entirely sure the best way to go about it. Is the idea to just really force the velocity of that onto the slope?
Alright so, I implemented a dictionary to accomplish this, but it didn't seem to help much. I could be doing something wrong. It's supposed to set the bool in the dictionary to true after pinging once, preventing it from pinging again. But for some reason it doesn't seem to change it to true until after it pings twice? https://hastebin.com/share/acezabajug.csharp https://streamable.com/h2nzm3
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Actually, I think what I may be having trouble with is that the Character Controller already does some sloping logic, and I think that's actually creating problems
not sure how it will work for you but here is how I do it . just realized naming was pretty bad when I made it, should've called the method AdjustForSlopes or something 😅
private Vector3 Move(Vector3 velocity)
{
if(Physics.Raycast(transform.position, Vector3.down, out var hitInfo, 1.5f, groundedLayers))
{
var slopeRotation = Quaternion.FromToRotation(Vector3.up, hitInfo.normal);
var adjustVel = slopeRotation * velocity;
if(adjustVel.y < 0)
{
return adjustVel;
}
}
return velocity;
}```
cc.Move((moveInput.y * currentMovementSpeed * Time.deltaTime) * Move(transform.forward) +( playerVelocity * Time.deltaTime));
I'll play around with that ty
After adding some text that displays the rayAngle, it seems that something is going wrong with the angle calculations, not the difference detection. https://hastebin.com/share/ifopumamup.csharp https://streamable.com/khuiw6
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
@dense estuary I haven't looked at the new codes you posted. But going through the first code you posted here, https://hastebin.com/share/cabacuvequ.csharp
I assume the calculations are correct here?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
There are several ways you could do that. Since you're going with the dictionary way. (Still using your first code posted)
Add this in your radar class:
`private Dictionary<GameObject, bool> pingedObjects = new Dictionary<GameObject, bool>();
private float lastResetAngle = 0f;`
And in RadarFunctionality(),
`if (rayAngle < lastResetAngle)
{
pingedObjects.Clear();
}
lastResetAngle = rayAngle;`
^ You could either clear the dictionary or reset all values to false, I'll leave that to you
In the for code block add:
`GameObject detectedObject = results[i].gameObject;
bool hasBeenPinged = false;
if (!pingedObjects.TryGetValue(detectedObject, out hasBeenPinged) || !hasBeenPinged)
{ // the rest of the codes`
*On edit:
Also don't forget to update the ping status or whatever you want to call it to true in the if block.
I have figured it out. Coroutines are a bit confusing for me, since I am using a coroutine for the entire thing, the rayAngle variable can't change until the coroutine reruns the while loop, and while the icon is fading out the coroutine is stuck. So to solve this I am starting another coroutine when it gets detected.
I feel so dumb but now it makes so much sense
While I was using the timer to fade out the icon, the coroutine couldnt change the rayAngle variable. So by putting the fadeOut into another coroutine instead, it prevents the rayAngle variable from getting stuck.
Ah
So, the dictionary system is working now aswell.
incase the detection range is too large, it will still only ping once
Glad you figured it out. Even I've learned something 😅
I was kinda building a similar thing , but for a mini map where the shots were coming from the enemies, like in the battle royale games on mobile.
Anyone know if their is a way to grab all player prefs keys? i guess somthing like this even though it does not exsist string[] allKeys = PlayerPrefs.keys;
nope
better off inplementing your own system and using json
dang alright
when i have a class Item item; and inside Item i have a reference to a ScriptableObject called ItemData itemData
is there an easy way to save item to json and when loading again it automatically links to ItemData again?
like, maybe json storing the asset path of the ScriptableObject or so?
or do i need to create a lookup table or so?
binary instead of json would also be fine
maybe i could make them Addressables and store the path?
why is a script's awake function executing before another script's start even though the the start script has a lower default execution order?
they are on two separate scenes that are running at once
but it shouldnt matter? unless it runs one scene first before moving to the next
if you want a chain of functions where execution orders matter, then have a public static event on the script that shall execute first, and then invoke the event and the others do something when the event is called
what about OnEnable? seems like its happening before my singleton's awake
also on order -5 while the enable is 0
Are you unable to add to a list of a struct inside another struct?
I can't really seem to find a solid answer on google but I am unable to add this struct to the items list
I'm not familiar with that error, but if you are going to be adding stuff to the collection then I'd rather use a List than an Array
Is this even unity tho
I am pretty sure that's where I was blanking and just couldn't figure out what I was doing wrong because I've been staring at code too much
Yes it is
I am wanting to move items inside a list, so i need a for loop for it. Now I am using it inside a while (elapsedTime < 1f), which is inside a coroutine as well. Am I doing it right or is there a better way of doing it?
But how are these things related? Moving things inside a list and using a coroutine
It's unclear to me what you want to do, can you elaborate?
Its for moving set of pieces which are also in a list. Consider 5 elements and I have to move them in a certain order.
The coroutine is responsible for moving the pieces, updating their target positions
while loop is for making it move within a fraction of time
and for loop to iterate in the list
Yeah a for and while should do it
I am making a match 4 based game
As long as you yield inside the while
in which if u swipe, all that elements in row or column must shift by 1 posiition
then im good i guess
i did a yield return null
Yeah this sounds fine
For reference: https://pastecode.io/s/0c6sb7tu
In this, i made the last element to move to 1st element's position, since they are on opposite screens, i manually made them wrap around the opposite screen by first making it move to end of bounds, then changing the target position.
For the middle elements (except the last element) i made a list of target positions and im planning for loop so they move and shift to other element's position and rotational alignment
weird interaction with this 1/10 placement issue... any ideas? taken from codemonkey
uhhhhh in the ui anybody know how to tile an image in one axis and is stretched in another?
cause wrap mode per axis seems to be not working
Primitive arrays aren't dynamic sizing so you cannot add an element to it.cs int[] data = ...; data.Add(...);//Error!The warning implies that it (the primitive array), referenced as a list interface (who knows why.. maybe implicit casting etc) could not access it's underlying implementation of Add - because it (implicit cast to the Array class type) doesn't actually implement one.
tldr: That isn't an items list. That's an items array. Use List<WeightedItem> instead.
was creating a pause menu until i discovered this bug where the player jumps even while in the pause menu and turns it off. It does not happen when i pause and unpause the game using the escape keybind which i made. When you first press the resume button, it triggers there and is a hassle. Anyone know what went wrong there?
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ur gud just helps with readability
from my opinion it looks like your bool is kind of flopped. if i follow the update code, if paused is true, then execute Pause(), which sets paused to true
same with the Resume function. I could be wrong, but try switching those first
i just did it for symmerty with the resume function
actually...
but that shouldnt affect anything right
it's just assigning it again, it may look wrong but it doesnt make a difference
okay, jus makin sure, usually anything written over is gonna be in update, rather than a method being called once in this case.
you can test it out thats the only surefire method, other than that im not too sure
oh wait so instead of it having to check for it evvery single frams, i could just make it check the instance i call that method
isnt that right
ehh not what i was gettin at, instead of the places you put ```cspublic void Pause()
{
pauseScreen.SetActive(true);
Time.timeScale = 0;
paused = true;
}
public void Resume()
{
pauseScreen.SetActive(false);
Time.timeScale = 1;
paused = false;
}
instead put
``` cs
public void Pause()
{
pauseScreen.SetActive(true);
Time.timeScale = 0;
paused = false;
}
public void Resume()
{
pauseScreen.SetActive(false);
Time.timeScale = 1;
paused = true;
}
try this and see if theres a better outcome. the more i read it the more it doesnt make sense though
i feel like your bool 'paused' should be set to true in order to enable the use of the Pause() class, instead of calling it inside the class. it seems repetitive
currently when you check if 'paused' is true, you still set that 'paused' variable to true, so it doesnt make sense to have it there. same with the other class. @night comet
looks like it aint got no gas in it
lol, yea that didnt work, after i reread my edit i thought it wouldnt work facepalm
sweett lol onward young lad
hehe
lemme look further
thanks for the help tho, i kinda know how to fix it now but idk if im wise enough to do it 😭
lol id take out the paused set code, it seems arbitrary if i use that word correctly.
idk how to help tho, i have to watch you bleed out hehe
Hi Folks, I am making a match 4 based game in which if If we swipe in a direction, all the elements of that row or column will shift to the next position. And the last element will wrapped to other side of screen and move to 1st item's position.
But I am facing an issue, I have a coroutine in which I have 2 while loops. The 1st while loop is responsbile for moving the last item to the end of bounds.min or bounds.max depending upon swipe direction, it also has a for loop which iterates over the other items and shifts them.
The 2nd while loop is responsible for moving the last item to 1st item's position as it changes the target position.
Problem: Earlier I didnt have this for loop so My last element was properly moving and shifting to the 1st item's position. But now with the for loop, other items are shifting correctly but the last element doesnt reach the 1st item's position, it stops just before it
Code: https://pastecode.io/s/cf3b18h8
(Refer 69th line)
So I want to remove some elements from a list in a loop
Should I rather create a second list where I assing what am I going to remove in the end
or iterate backwards removing elements?
iterate backwards
So im having the same issue as the guy in this Topic, and i still haven't found a solution, im trying to use UnityEngine.InputSystem in an External Assembly but when i try to get the Scroll wheel (which is a Vector2), I get an error: "error CS0012: The type 'Vector2' is defined in an assembly that is not referenced. You must add a reference to assembly 'UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.", and when i add a CoreModule Reference it just wont build.
And why wont it build?
Hold on
error CS0433: The type 'Vector2' exists in both 'UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
error CS0234: The type or namespace name 'CoreModule' does not exist in the namespace 'UnityEngine' (are you missing an assembly reference?)
error CS0433: The type 'MonoBehaviour' exists in both 'UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
error CS0433: The type 'GameObject' exists in both 'UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
error CS0433: The type 'Rect' exists in both 'UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
post your .csproj file to a paste site
so you are using the .dlls from the wrong place. You need something like this
<Reference Include="UnityEngine">
<HintPath>C:\Program Files\Unity\Hub\Editor\6000.0.23f1\Editor\Data\Managed\UnityEngine\UnityEngine.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="UnityEngine.AnimationModule">
<HintPath>C:\Program Files\Unity\Hub\Editor\6000.0.23f1\Editor\Data\Managed\UnityEngine\UnityEngine.AnimationModule.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="UnityEngine.CoreModule">
<HintPath>C:\Program Files\Unity\Hub\Editor\6000.0.23f1\Editor\Data\Managed\UnityEngine\UnityEngine.CoreModule.dll</HintPath>
<Private>False</Private>
</Reference>
Sure, ill try it
But the dlls work and i just copied them from my unity 6 install to the Libs folder
did you copy the right ones though, there are multiple versions of the dll's
There are? I only found one UnityEngine.CoreModule, but sure ill look again
multiple UnityEngine which is what is giving you the problem
can anyone help me out?
Whats a reasonable way to calculate Vector2 out of Vector3?
Currently a character is moving on X and Z axis(Y axis is for jumping)
But when converting to Vector2 X/Y are used, is there a way to swap it somehow?
Since a character moves ona flat terrain I'd like to use x/y for movement, even input system uses x/y when asked for Vector2, we are converting it:
Vector3 movement = new Vector3(MovementInput.x, 0f, MovementInput.y).normalized;
But I want to calculate the direction from enemy and the player, do I have to manually convert it from Vector3 to Vector2 in order to do that?
Not sure where to put this question but
- I edit the prefab
- CTRL + S
- Run the game and it works
- Open prefab, and changes are not there
- Run the game again and it doesnt work
How is that possible?
Since its not code related then probably #💻┃unity-talk
you can create extension methods if you want, like
public static class Vector3Extensions {
public static Vector2 XZ(this Vector3 v) => new Vector2(v.x, v.z);
}
public static class Vector2Extensions {
public static Vector3 X0Y(this Vector2 v) => new Vector2(v.x, 0f, v.y);
}
then do
var myVec = new Vector3(bla bla bla);
var vec2 = myVec.XZ(); // Convert to Vector2
var vec3 = vec2.X0Y(); // Convert to Vector3
Thanks, I will give it a go 😄
Btw when creating those, do you put them in 1 file or make a file per extension(i.e. 1 file for V2 and one for V3)
I usually make a file per extension class but it is not a rule
when I make a new class in VS2022 it asks for a class name/file name so I always assumed its expecting 1 class per file(even tho I tend to have multiple if those are smaller classes/structs that are used within the main class)
That sounds reasonable, who knows I might have more extensions in the future 😄
VS does not care how many classes/structs/enums you put in one file, Unity does though
Unity if its a monobehaviour right?
but I can have a monobehavior + regular class I assume
not just monobehaviour, anything deriving from a Unity Object
Makes sense, otherwise unity would get confused 😄
Need help with mesh generation, I'm using Unity splines with a custom class to generate a road mesh with T-junctions and intersects and now I want to generate sidewalks but I'm struggling on the intersections and preventing overlap
Any advice is appreciated. Will post my code later as I'm AFK
What would be the best way to limit Vector2 movement to one direction with the newer input system? I am trying to replicate the movement way/feel of an old-gen Pokémon game, and I want for the player to walk in one direction/axis based on the first button pressed + held down, ignoring the other walk inputs pressed after (until the first button is released). Is there an automated way to do this, provided already in the Unity Editor, or is this something that needs to be coded separately?
simplest way I can this is on the first button pressed, get the direction and set a bool to true, while that bool is true you don't change the direction, this might need tweaking depending on your desired behaviour as what I've described would work no matter which button is pressed as long as it remains pressed, another one is reading the current input by splitting the Vector into the two axes and say you press forward, then moveInput.y == 1 and as long as it is one then your direction stays Vector2(0, 1) it comes down to stroing what the first move input value was and seeeing if any of that remains the same before changing it
On the off chance anyone could help me with animations, I've got the code and everything work. But I think I simply don't understand what I'm doing on the animator side. I've got a switch which should interact with a door, the switch animation works but I can't get the door to work with it.
I've tried so many different transitions im just at the point I probably need to step away from it.
Need help with mesh generation, I'm using Unity splines with a custom class to generate a road mesh with T-junctions and intersects and now I want to generate sidewalks but I'm struggling on the intersections and preventing overlap
Any advice is appreciated. Will post my code later as I'm AFK
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.
can you explain what animation idle last frame is?
also you have no reference to the animator component
I think I was just getting confused, would it be better if I send a video.
It would be correct to add this to the door script?
It was more meant to be idle that part you mentioned. I tried just having open and closed and looped between the two but yeah im confused.
How could I get a list of all the vertices on this loop?
You should use Unity.Mathematics float3 and float2 structs. They define all these extensions and make your code really pretty
e.g. float3.xy = float2(x, y), float3.xxyy = float4(x,x,y,y,). It also has a bunch of implicit casting to and from int3 and Vector3
Hi, how do you organize object interaction?
For example, on my multiplayer game, I have a common object, a car with screws.
My player can take a screwdriver, and screw in the car's wheels. Would you put the “screwing” script on the wheel or on the wheel itself?
as you will need both the wheel and the axel I would put it on the object which is parent of both
You should have a screw script on the object that is being screwed and the "screwing" which I believe is the action should be on the screwdriver.
hello
im making a level editor
how do i snap things correctly?
i just want to snap things every block, i have tried a lot of method
please type in full sentences
sorry
RaycastHit hit;
Ray ray = GetComponent<Camera>().ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, Cart_Create_FarPlane))
- I do Raycast
Then i instantiate
instantiated = Instantiate(BuildingGameObjects[WhatBuildingGameObjectDidWeSelectLast], SnapToGrid(hit.point), Quaternion.identity);
I made a custom Vector3 function
Vector3 SnapToGrid(Vector3 position)
{
float x = Mathf.Floor(position.x + 0.5f);
float y = Mathf.Floor(position.y + 0.5f);
float z = Mathf.Floor(position.z + 0.5f);
return new Vector3(x, y, z);
}
Problem arises, i can place blocks (or anything like spheres) on x,y and z axis
But, when i go oposite to them i cannot place blocks anymore and it just places right inside the object that we hit.
Can anyone point me in the right direction about Timeline Signal Emitters and Receivers?
I kinda need to use a Signal that has 3 parameters, but insofar it seems to me that in how Timelines and Signals are set up - you can only ever squeeze just one.
So far I've tried:
- Creating a custom signal with 1 parameter (worked, as seen on the screenshot - both int and bool methods appear in Function selection in the signal receiver)
- Creating a custom signal with 3 parameters (didn't work, the matching functions do not appear in the receiver selection)
- Creating a struct and building an emitter with it (didn't work, same as above)
- Creating both an emitter and a receiver that works around a struct (didn't work, same as above)
Is this system even flexible enough to support more than 1 parameter? Am I missing something?
It would be a lot easier to use Unity's Grid component
how??
isnt it in 2d?
the grid has 3 axis is not 2d
I HAVE FINNALY GOT IT
oh my daysss
it was a lot more than what u guys think
too much to explain, but thank you for helping, see ya :o
Hi !! Is there anyone who wants to help me fix my bugs on a project? I'm trying to create a dialog system in tools on unity, but every time I have a problem with the save graph of the tool... And I don't know how to do it anymore
Hey, I've got a question regarding a class-based state machine. Can anyone help me?
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
#💻┃unity-talk message
read the entire bot message
noone's gonna be able to help you if you don't say what you need help with
Gotcha. If I'm creating enemies that are generally similar (they will all have amble, chase, and attack states), but they have different types of attacks, and some have multiple attacks, should I use one state machine to do this? Or would I need to create a new state machine for each enemy? How would I go about using one machine for different enemy types?
you could split it into 2 parts, 1 part being the core state for when to display what behavior, and then another part specifying subbehavior within a specific state (ie, attacking)
Right, if I understand correctly, I may have that concept already. I have one 'base' class, and then three extra classes derived from the 'base' class which can then transition into each other. I'm not advanced enough in programming to figure this all out myself, so I've been using Finite State Machine tutorials, but none of them seem to have my specific use case. My enemies are all pretty different, but will use some of the same general logic, so I just want to keep it as concise as possible.
what are those three extra classes? wdym by "transition into each other"?
They're the three different states: amble, chase, and attack. Inside each of those classes, whenever a certain criteria is met (i.e. player enters the chase or attack distance) it will transition into the appropriate state using a function (DoState) from the base class.
my problem is that I want each state to behave differently for each type of enemy, and I'm not too sure how to implement that
so you have 3 separate components, which you're applying all of them to a given enemy?
a state machine centralizes the state, doesn't really seem like you have that here, that might make it hard to manage or modify
If you mean component as in a GameObject component, no, I only put the base class onto the enemy, and the 3 extra state classes derive from that base class, so they can reference each other without having to be attached to a gameobject
that doesn't really make sense
is the base class aware of the 3 other classes?
or what exactly is going on here?
or are you mixing/conflating inheritance and composition?
I've spent a while now trying to implement a way to constrain the rotation of a Vector3, and currently I have a beautifully working swing constraint implemented thanks to a stackoverflow post. In the screenshot, the cone indicates the maximum rotation away from the "initial" direction, currently 22.5 degrees. "Final" is the "target" vector constrained to that cone.
Honestly, this may be a bit above my skill level, and I can't answer with full certainty, so I'll say that this is solved for now, and then ask later if I need any more specific help. I'll continue researching for now, and thanks for your help!
My question is how can I modify this constraint so that the the maximum swing angle differs between the local x and y axes.
The first screenshot shows the same cone but facing towards the camera. The "Up" vector would be a vector orthogonal to the initial direction, and passed as a parameter when using the method. The second screenshot is what I am trying to do, where the maximum angle along the local x-axis is less than the maximum angle along the local y-axis.
I have tried various ways of achieving this over the last few days but nothing so far has worked correctly. I have looked far and wide online and have just come up empty. My last hope is that someone here may have an idea of how to do this, but if not then I'm ready to consign myself to just using the original "LimitSwing" implementation.
so you're trying to constrain the angle on an ellipse? what about getting the angle and clamping it to the corresponding point on the ellipse?
probably not the most elegant solution but i think it'd probably work
https://math.stackexchange.com/questions/22064/calculating-a-point-that-lies-on-an-ellipse-given-an-angle
doesn't seem to be a channel for this, so I'll ask here.
How do I prevent VS from autocomplete if I don't press tab/enter?
In the screenshot, let's suppose I want to name my method "Mo" (bad name, I know, just an example)
The moment I press the ( key, it autocompletes to "onAnimatorMove", forcing me to ctrl+Z then filling it again manually.
it should be configurable, try searching for "autocomplete" in options
found it, thanks
I had briefly considered doing something like that yesterday, but at the time I assumed it wouldn't work if the target direction fell "within" the ellipse (I hadn't slept the night before, so my reasoning skills were missing lol). After thinking about it again though, I guess I could project the target position onto a plane using the normalized direction, and only use the x/y equations in that post if the position falls within the ellipse.
I'll give it a go, thanks!
Would people consider ChatGPT good for looking at code, and knowing how to fix it? Or are there better bots out there?
Anyone know how I can do this? I can generate it along the uncurved area but once it reaches the curve I don't know
I'm trying to generate a sidewalk in what is essentially outlining the shape so even if you have a link to somewhere that I can read up on that I'd appreciate it
no, and no
chatgpt is good at being convincing, not at being right. same for other chatbots.
it's nice to auto comment your code ʷᶦᵗʰ ᵐᵒᵈᵉʳᵃᵗᶦᵒⁿ
Ah
a lot of chatgpt-generated comments ive seen so far are... questionable
chatgpt doesn't really see the "with moderation" part lol
I've been using ChatGPT for a gun script and while it did have some errors, I've been able to get pretty far
essentially anything it tells you, you'd still need to verify it as LLM's work by giving you the statistically most likely answer to the question you feed it
What does that mean?
don't rely on it. you'll need to learn to do stuff yourself as well
Okay
chatgpt guesses everything. (except i guess math stuff that's recently been offloaded to python)
Ohh
it's a really good guesser, but guessing will never be 100%
it's great if you need to ask about code, like a function or something as it can reference the code docs it was likely trained on but overreliance on it is a crutch
and it can be a handy starting point, if you encounter a problem you don't know how to solve, ChatGPT might be able to steer you in the right direction to find your answer
Thank you!
In the end it's a tool and so long as you know the tools limitations you can make excellent use of it, but for now your best bets to coding are Google and StackOverflow
how do I hide all these projects? They're showing up in my solution view
Okay! Thank you so much
One of these I think?
oh nvm uncheck the Registry Packages
The first two is correct , you have to delete them though so they can regen just the ones you marked
Otherwise you will still have the same csproj files
ah ok
Thanks
Hey, i have a game where there is a chat. Whenever the player types in the chatbox, the keys can still trigger movement and other things. Is there a way to disable inputs for everything else when writing in an input field?
please don't crosspost
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
does anyone know why my notes are instantiating double and in unexpected positions sometimes based on this code
Debug.Log to see if line 11 is running more than once
Either line 11 is running multiple times, or you subscribed to the event more than once
okay
Ok - but without seeing more code and understanding when and where for example GreenAudioPeaks() runs, it's impossible to say with the information you've given thus far.
As for the posiiton it will always spawn wherever GreenNoteSpawnPoint.position; is
so presumably you've put that obejct somewhere incorrectly
In update of what though? We don't even know what script this is, which object(s) it's attached to, etc.
the green note spawn point stays in the same place ive kept my eye on it
clearly not
Or if it does, something is moving the notes afterwards
Also why do you do this?
GameObject InstantiatedGreenNote = Instantiate(GreenNotePrefab);
InstantiatedGreenNote.transform.position = GreenNoteSpawnPoint.position;
InstantiatedGreenNote.transform.parent = this.transform;```
instead of just:
```cs
GameObject InstantiatedGreenNote = Instantiate(GreenNotePrefab, GreenNoteSpawnPoint.position, GreenNoteSpawnPoint.rotation, this.transform);```
doing it like that fixes it
is there something wrong with my raycast? im trying to do the raycast illustrated in the attached image and return the position at the end if the ray doesnt hit anything, but the ray seems to always hit something even when there is nothing
the bounds colliders are also visible in the image
Vector3 randomDirection = Random.insideUnitCircle.normalized;
Vector3 enemyPosition = _player.transform.position + randomDirection * _enemySpawnDistance;
Debug.Log("trying to spawn enemy at " + enemyPosition);
RaycastHit2D hit = Physics2D.Raycast(
_player.transform.position,
randomDirection,
_enemySpawnDistance,
LayerMask.NameToLayer("Bounds")
);
if (hit.collider == null)
return enemyPosition;
else
{
Debug.Log("enemy raycast hit wall");
return Vector3.zero;
}
that fixed it, thank you!
Oops wrong chat.
Hey yall. I know this is not the help section BUT I CANT FIND IT FOR THE LIFE OF ME!!!!
So right now I have a prototype ready but every time my friend plays the build it either doesnt load anything/ Loads the models but not the colliders/Loads everything but the scripts/Doesnt open/The Player model starting ascending to the white light
Now I have no idea what this is but it would do this everytime he tried to load it. On mine and everyone else, it works fine. Any ideas???
Specs:
NVIDIA GeForce RTX 3060 Ti
11th Gen Intel(R) Core(TM) i7-117DDF @ 2.50GHz
Windows 11
not a code question. Move to #💻┃unity-talk
In the meantime make a development build and then look at the player log for errors
there arent any sadly
A video of the issue would be helpful.
yeah would be if my friend would listen
We don't have any power over your friend either.🤷♂️
would hope you knew that...
Sadly, I don't poses any remote screen or thought reading abilities.
It's like calling a doctor and telling them "my friend has pains in the back, but sometimes they're in the the stomach or chest and sometimes in the left or the right leg, but my friend doesn't want to go to the hospital and do any checks".
Obviously, no one would be able to help your friend even if it's the most professional doctor in the universe.
i want to align my shot impacts to the hit normal, but if don't use complex mesh colliders, the impact rotation is wrong on (simple box colliders) and doesn't fit to the mesh, and if i use the shots rotation, and the shot hits a side, the impact rotation is wrong again... any ideas?
It really just depends how your prefab is laid out and the code you use
whatever that means
that there is no one-solves-all solution for this
i know
that's why i said ideas
our ideas can vary very heavily depending on what your setup looks like
if you have simple meshes it can be easy, if you put a box collider around a complicated mesh that might be nearly impossible
no simple meshes, that's why i even ask, but it's an rts, which means i can't give em all each a precise mesh collider
but for simple to semi complicated meshes:
- Put a mesh collider on your mesh dont let your bullets collide with it (untick in collision matrix)
- Send a raycast from impact point in the direction of -normal of the impact point
- If that raycast hits the original mesh display the impact hit on that point + figure out the normal of that point
the only important thing would be performance with hundreds of shot's hitting every second
well my only other idea would be creating an LOD variant of your mesh and using a mesh collider with that
is it a deforming mesh or static?
static for now
i had an idea rn, i could use a capsule collider for impacts (there are no edges to mess the impact rotation up) but wouldn't that also have bad performance? idk how complex round colliders are
its sphere > box > capsule > mesh
but hundreds of bullets per seconds should still not let unity break a sweat
It means if your prefab is laid out such that its local Up axis aligns with the graphic you want to show, you spawn it with a rotation such that its up axis aligns with the surface normal. Likewise for whatever local direction the prefab is arrayed in
unless you are doing other heavy stuff on impact
Sphere has the best performance BTW
Sphere has the simplest math
ah right, just a distance check
ok i will generate a capsule collider for each unit, and set it on or off based on if the (energy)shield is on or off (the shield impact is a 2d sprite with an offset to the target, that's why the rotation is important) idk if there is a better code way to do it but whatever
hol up but now collisions are broken and collide with the shield... uhh
You need layer based collisions
ok yes true
my only 3 codes that correlates to shooting or enemy
you have Error Pause enabled
and theres an error... check that error and you'll have ur answer
oh.. sorry thanks for the help
what can be the main reasons my bullet aint registering as an hit / when colliding enemy not taking dmg
use debug.log to find that out
i put a debug.log on this and nothing is happening in console, i thought it could be the tag so i tried to change that as well but idk what else the problem may be
put log before if statement
also the 3 dots in your IDE is making a suggestion, give those a look when they appear
like this?
yes click Show potential fixes (btw this is unrelated for current probalem but good for future)
consider using comparetag
keep in kind OnCollisionEnter needs a rigidbody to actually get called
i think this that issues problem, thanks
thats not the issue
the function does the same exact thing, just compare tag is more efficient
the if tag would not change how the OnCollision works
looks fine
maybe would just change < to <=
unless you don't want this thing to die if it just touches 0
when it "dies" i think it spawns it out for the other prefab i have for it but not the correct transformation?
this error happens after 4 hits so basically when it "dies"
which one is line 22 inside OnImpact
if its target.ApplyDamage its probably because you have something hit tagged Enemy that doesn't have EnemyTarget component
you should consider adding a null check first, or if(collision.collider.TryGetComponent(out EnemyTarget target))
but fixing the core issue is more important, why is it that something you tagged enemy doesn't have that component
if all your enemies will have that component the tag is pretty much useless, you can just check the component directly
tbh im only gonna have one enemy
regardless you can replace the CompareTag if with this #archived-code-general message
yes you can now remove that line entirely
since target comes from If component has been found
the enemytarget line
yes the one doing GetComponent, as TryGetComponent is just a replacement with an null check inside (hence the TryGet and returns a bool if found stored in out )
ah ye i see that has removed that error now
but i dont understand taht when it dies why it wont replace the prefab
wdym replace the prefab?
prefabs are nothing more than blueprints to a gameobject , they are not really anything else but an asset
they don't exist in runtime
hey, what am I doing wrong here, I want to take a "screenshot" of my objects and save them in png with transparent background but instead the background is black
RenderTexture rt = new RenderTexture(512, 512, 24, RenderTextureFormat.ARGB32);
rt.antiAliasing = 8;
Camera screenshotCamera = Camera.main;
screenshotCamera.targetTexture = rt;
screenshotCamera.clearFlags = CameraClearFlags.SolidColor;
screenshotCamera.backgroundColor = new Color(0, 0, 0, 0);
Texture2D screenshotTexture = new Texture2D(512, 512, TextureFormat.RGBA32, false);
screenshotCamera.Render();
RenderTexture.active = rt;
screenshotTexture.ReadPixels(new Rect(0, 0, 512, 512), 0, 0);
screenshotTexture.Apply();
byte[] screenshotBytes = screenshotTexture.EncodeToPNG();
SaveScreenshotOnDisk(screenshotBytes, name, path);
screenshotCamera.targetTexture = null;
RenderTexture.active = null;
Destroy(rt);
Destroy(screenshotTexture);
return screenshotBytes;
tryna make it so when it dies it swaps over to the other prefab (which just takes it rotate 90 on the x so it looks dead)
thanks!
shameless plug lmao
run debug logs to make sure everything is working
so its not spawning ?
ye its not spawning and the enemy wont get deleted when health reaches 0
okay you know the drill by now.
put a Debug.Log(health, this) before the if statement
logging is the way we start singling out issues and making sure things are what we expect them to be
damage is working
check the heirarchy if the gameobject has spawned at all, does the prefab you spawn have any scripts etc.
I know how painful it is to create a bunch of icons / images from 3D objects by manually screenshotting. Thought one day someone could use the help 😛
it does spawn adn remove the other one
okay looking at the code of that plugin we do pretty much the same thing so I don't get it why it doesn't work
oh more of like, check the sample/example scene. make its the setting on the camera
I'd have to double check but probably something to do with the background color / sprite mode chosen
since you're rendering a texture and not as sprite? transparency is on by default if sprite2d is chosen as type rather than texture when you explicitly have to check "has transparency"
just a guess though
yeah I'm not saying the plugin is bad or anything, I know nothing about making screenshots so I do not know how hard it is
na yea I know didn't mean anything by it lol it actually isn't hard at all, just like some basic things in unity, just tedious to do manually esp labeling them and switching their texture mode to sprite
programmer life -> spend 2 days(sometimes) automating something to take a few seconds rather than a few minutes of manual work 
and then you realize someone else already made it better so you just use their package instead 
and that kids, is how javascript was created
its replacing the deadbody now with the correct rotation but its going to a set location and not where the enemy died, any reason why?
when i add this "transform.position, transform.rotation " to the Instantiate code it messes with the rotation of the prefab thats meant to spawn when the enemy dies
oh so you want the rotation of the original prefab?
just add that as .rotation then
Instantiate(prefab, myPosition, prefab.rotation)
Hello can anyone fix me this error? I get in the error logs that my string array doesnt exist but i declared it outside methods in the class like this (public string[] STRINGS;)
show the error + related code
is this what you meant
ops. you need .transform.rotation
i usually have a prefab as Transform if its not a component
once i do that it dont rotate it at all
just falls through map
kinda
is the rotation correct though? its probably needs offsetting in the position
it does rotate, it just rotates to the original orientation of the prefab
my prefab settings
oh wait nvm.. i forgot the collider..
sorry for troubling you guys!
https://paste.ofcode.org/3bzi8vssvxApVZDafVBMfWp
Hey hey!
So i basically wrote this script.
i'm still a noob at unity/C# so i'll write down how it's supposed to work.
I press on indicatorheatmap (which is a big arrow) and it moves to a new position with the cam. ( already did this with click event and works fine)
However i have 3 heatmaps which are 3D graphs that need to start invisible. When i click on the primary button with the indicator heatmap, the first heatmap should popup then press secondary button to cycle between heatmaps that fade in and out with eas in/out for 5 secs.
whenever i click play mode it does NOT start invisble or work at all. Anyone know what im doing wrong?
The heatmaps have mesh renderers. I couldn't add a material for some reason. Could someone check the code ands ettings?
this is my hierarchy, Heatmaps is an empty object with the script attached to it.
Hello. This script works fine on the unity play mode, but doesnt work in build. it still rotates, but nothing happens when it hits the player. can anyone help? ty
Hi i have a problem, why my code doesn't work?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public float speed = 5f;
public Rigidbody rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
float v = Input.GetAxis("Vertical");
float h = Input.GetAxis("Horizontal");
Vector3 vector = new Vector3(h * speed , 0.0f , v * speed);
Debug.Log(vector);
rb.AddForce(vector * Time.deltaTime);
}
}
"doesn't work" isn't very explicit. Do you get the debug log in the console? Errors?
Make sure you attached the script on an active object in the scene
And that the script is itself enabled
Switch to the Console tab and see what's in there
Also since you drag-drop the Rigidbody in the Inspector, you do not need the GetComponent<Rigidbody>() in void Start()
ok, so i will delete it
The script attached to the object is not the one you're looking at in your code editor. The object and script is active, but you get no errors nor logs. The console is not filtered either
Select the script file from Unity and look at its contents with the Inspector. The Obvious™️, make sure you saved your changes
It's not the same piece of code compared to what you posted, there's no Debug.Log() in void Update()
Make sure you don't edit out the code before posting it here, it will mess up the line numbers and/or its behavior
Don't. I was using this to see if the code was running or not
Put one in Start() and another in Update() and try again
Ok, i'm going to do it
I need help with my unity options. When I try to create a C# script there's no option for "Create C# Script"
The location may have changed in the recent updates. Make sure you're right-clicking inside the Project tab.
It may be in a sub-menu of some sort
It was renamed to "MonoBehaviour Script"
Good, your code runs
why did Start show so many times though
Which means you're not adding enough force, or something else (ie. another script) is moving the object
yea, was the force
thanks
now is turn to do the animations jaja
is this movement normal?
code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public float speed = 50000f;
public Rigidbody rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
Debug.Log("Start");
}
// Update is called once per frame
void Update()
{
float v = Input.GetAxis("Vertical");
float h = Input.GetAxis("Horizontal");
Debug.Log("Update");
Vector3 vector = new Vector3(h * speed , 0.0f , v * speed);
rb.AddForce(vector * Time.deltaTime);
}
}
well your cube rolls over because you apply force, you could use rb.MovePosition instead or freeze the rotation of your cube
ok
Would definitely freeze the rotation if you don't need that. MovePosition does not really respect physics as it's no better than transform.position physics wise
i would not say they are same, even tho MovePosition does not give 100% accurate collisions. it can still be tuned with collision detection which you can´t do with transform position since it only teleports your object.
but i would probably not use MovePosition either
you will have to see which method you want to use.
MovePosition will accurately knock other objects out of the way when used with a kinematic body but the body being moved will not be stopped by other objects
I'm trying to plot a point on a NavMesh by trying to use the NavMesh.SamplePosition function. The expectation is that, because the NavMesh is only slightly higher than the plane it's being plotted on, the NavMesh hit I should be getting is the same point only with a slightly elevated y coordinate. For what ever reason, though, the actual NavMeshHit is thousands of miles away and I don't know why or how to fix this. There is a NavMesh space just above the point where it's supposed to be plotted for it to occupy, so why isn't it occupying it?
The most likely answer is your code is sampling from a point far different from what you expect
How so? The point I'm trying to sample is (-10, 0, 0) and I'm expecting it to be (-10, 0.17, 0) but it's instead (-10, 0.17, 5.67). I don't know why this is
perhaps local vs global position?
I don't know why that would make a difference. I made absolute sure these are the coordinates in global space
Unless...
it would make a difference if you were basing one check on local coords while the other check was on global coords
i can't tell if there's a relevant local position here, but if there was, it'd be at z=-5.67 i think
so maybe that's something to check for
Now the point it spits out is (-10, 0.83, 10) instead of (-10, 0.17, 5.67)
well, what changed?
It's different, but it shifted even further away for some reason
I shifted the point I wanted to sample to space local to the character
shouldn't it be local to the navmesh, if anything?
This is what I'm trying to do
for (int x = 0; x < 1; x++)
{
Vector3 translatedPoint = new Vector3(-projector.size.x / 2f + x * 0.1f, 0, -projector.size.y / 2f);
if (NavMesh.SamplePosition(transform.position + translatedPoint, out NavMeshHit hit, Mathf.Infinity, NavMesh.AllAreas))
{
//Print nodes at the hit point and the theoretical point
Instantiate(node, transform.position + hit.position, Quaternion.identity);
Instantiate(node, transform.position + translatedPoint, Quaternion.identity);
}
}```
The script is attached to a decal projector that is at the same global coordinate as the character it's attached to
...Wait
Oh I think I see where I messed up
There we go. I fixed it
Because it's supposed to iterate through a grid. This is there so I can test the first instance and the first instance alone
Then easily convert to a grid
I'm trying to programatically render TextMeshPro text to a Render Texture in Unity, that is then attached to and OVROverlay for clear text in VR, using Nothke's RTUtils script (to render to a Render Texture directly without having to create a camera).
Nothke's RTUtils script: https://github.com/nothke/unity-utils/blob/master/Documentation~/RTUtils.md
When starting the program, the text displays for the first frame, but disappears as soon as everything else is initialized (the controllers show). I have been trying to troubleshoot this for a whole day, debugging the program to see if something isn't working as expected, and disabling things like the passthrough renderer to check if the text was being rendered behind somehow.
The only major thing that I've found is that the Mesh Renderer component the TextMeshPro object adds to the GameObject seems to be disabled during runtime, even when I set the renderer of the TextMeshPro object to true each frame. Is there any way to enable/reenable this component programmatically in a TextMeshPro class? I feel like that might be a major factor causing my text to disappear after the first frame. Maybe it's not rendering the text to the Render Texture properly because of this.
Below is the link to the relevant code that renders the TextMeshPro object to the Render Texture and attaches it to the OVROverlay (InitializeLocalization() populates the TextMeshPro object with the relevant text and font). I've also included screenshots of the components on the Startup Renderer object during runtime, along with screenshots of the behavior going on with the OVROverlay on the first frame vs the rest of the time (passthrough object disabled).
https://hastebin.com/share/eguyijigov.csharp
Let me know if any further information is needed.
public class MusicHandler : MonoBehaviour
{
[SerializeField] private List<AudioData> AudioData;
[SerializeField] private AudioSource audioSource;
Custom struct (AudioData). Anyone know why it wouldn't show in inspector?
my other class works. Just not this new one I made lol
using UnityEngine;
public struct AudioData
{
public string Name;
public AudioClip Clip;
public AudioData(string name, AudioClip clip)
{
Name = name;
Clip = clip;
}
}
Nothing fancy
struct must be marked as [Serializable]
is this a reasonable way to serialize a POCO into json or will I run into issues down the road https://paste.ofcode.org/329WgHH8vJjP7G9LQUfxev7
Is there anything particular you're worried about?
serialization between scenes and during crashes
im currently doing something similar to serialize SOs and i have issues sometimes with things not saving when alt f4ing etc
no idea what causes it since sometimes it works fine
Probably simply a matter of when you're saving the data. If it's before the crash/altf4, it would be saved. Otherwise, obviously not.
Is there a way to in editor add a button to game that will end the "play"
since application quit only works on compiled exe
Would anyone know why it feels like my player is stuck to the ground for the first jump? It causes them to do a little sticky hop at first.
You are using GetAxis which has smoothing. Try GetAxisRaw if you really want a hold button for jumping
Personally recommend GetKeyDown though
aha
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#endif
Figured it out
Wanted to be able to use/test my quit buttons lol
well it would be saved when the destructor for the Inventory class is called or OnApplicationQuit
not sure what else to do
- Are you sure any of these are called on alt F4?
- Test it out. Add some logs, make a build and test it out. See that the log files contain the expected logs.
so im making a skills system for a game with 3 classes, each class has two different archetypes. each archetype has 6 passives, 3 abilities, and each ability has 2 specializations. im storing which abilities are set active in a menu in a PlayerSkills singleton.
would i just have to hardcode a bunch of if(PlayerSkills.instance.blah blah) in my player combat scripts?
Maybe bind the data to the corresponding ui elements, so that manipulating the UI would update the corresponding data
Going through the Unity Essentials tutorials. When I double click the code files in Unity, it opens them in Visual Studio but it says that the project is incompatible:
Is this normal?
right click the solution/project, select reload with dependencies
also configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
When I click it, I get this:
Then when I press OK
It shows me this web page in the browser
And the project is the same in the browser
which version of VS
2022
then configure first
Okay
Hi! I have a cs Dictionary<Vector2Int, List<int>> I want to get a random integer with its respective Vector2Int from the dictionary. Each int should have the same chance of getting picked. I don't know how to achieve this, as every Vector2Int key has a different sized List<int> value
The "Element" in the picture represents a Vector2Int key
You can do a weighted random to choose the key, where the number of elements in the key's list is the weight and choose a random element within the list.
Alternatively, if you want a simple solution and don't care too much about performance, you can add all the ints and their key to a combined list and choose a random element out of that.
Thank you for your suggestion. I'll give it a whirl 😊
Yeah in order to do the higher jump I have to hold the jump key.
Can't I use structs as default parameters?
Default parameters must be constant. Just make another overload without that parameter that calls this one and passes Vector2Int.one to this
Constant values must be values that are known at compile time. Vector2Int.one is not known because it must call new Vector2. I suggest you make the parameter nullable and then assign a value if null.
Alternatively set the default value to default in order to automatically call new Vector2 if no value is supplied.
Thank you. Can you provide me with examples for both options?
Also not a bad option
Print value. It's probably a low value on initial press lol
Hi!
I need to find the following parameters of a DirectionalLight in HDRP for script.
- Temperature
- Intensity Multiplier
- Indirect Multiplier
I have searched in HD Additional Light Data(script) but I can't find any parameters with those names.
How can I access those variables via script?
Its a bit annoying that Unity doesnt always use the same variable name as shown in the inspector - you could try switching the inspector to Debug mode and search for the property that way, filtering by the type or you could also give them specific values and check that way - they should also be listed in a specific order that matches the inspector when viewing the source code for that component so if you know the property above/below the one your looking for you can search that way too - and some of them may require using a Set function from the component and not modifying the property directly
I have a player Rigidbody (physics need to be applied on them with constraints, water, etc so no CharacterController) and their movement is done with AddForce on them.
I'm trying to figure out a way to prevent the player accelerating unrestrained and deal with cases the player trying to slow down if flung without adding to their speed.
I doodled a picture to kinda get across what I'm doing: Red cross is (0,0), top black vector is the player's current velocity, bottom one is the velocity the player is trying to enact, magenta semi-circle is how fast the player can go on their own power, blue is as if I did nothing else to the desired velocity, green is the velocity I want to give to AddForce as it doesn't accelerate the player any faster.
- Is it possible to re-enable read/write mesh access via the .UploadMeshData method after disabling it? The mesh is procedural
The data is deleted from CPU memory if you pass markNoLongerReadable: true in that method. There's no way to retrieve it again. You can read from the GPU buffers directly, but it won't necessarily be 1:1 with what you had and it's not as simple to read as the original.
if (Input.GetKeyUp(KeyCode.Return))
Having issues: In editor (not compiled. haven't tested). But I can't get Input to see enter Key (non numpad) at all
Tried KeyCode.KeypadEnter for numpad also
and nada
Any ideas?
very doubtful the Input class works in editor mode
It does work in editor lol ```c#
if (Input.GetKey(KeyCode.LeftShift))
{
if (Input.GetKeyUp(KeyCode.BackQuote))
{
OnToggleDebug();
}
}
if (showConsole)
{
if (Input.GetKeyUp(KeyCode.KeypadEnter))
When you say editor it makes people think you're using it in a Editor or EditorWindow
Have you checked that that code is being run, because there should be nothing wrong with KeyCode.Return
aye
it is
Debug.Log("ShowConsole state: " + showConsole);
if (showConsole)
{
Debug.Log("In if(showconsole)");
if (Input.GetKeyUp(KeyCode.Return))
{
Debug.Log("return key up event");
OnReturn();
}
}
I'm curious if its because its a gui.textbox, which I don't know why input would matter
I mean TextField lol
ah yea. works when not focused. weird
weird lol
if (e.type == EventType.KeyDown)
{
Debug.Log(e.keyCode == KeyCode.None);
catches return/numpad enter in gui
Why are you using IMGUI?
for quick debug menu
well
console
quick rect + textfield that focuses control there when key group is pressed, then obviously handles input based on return
If you're reading from OnGUI you need to use Event, what Navarone linked earlier
Though I would recommend using UIToolkit instead of IMGUI for menus like these
I'll look into UI toolkit
Whats wrong with IMGUI btw? I don't typically use Unity, but I have used imgui in personal projects a bit.
It's being removed because UI Toolkit is the future of both Editor and Runtime UI in Unity
IE: I use unreal. Only using this out of force by class
ohhh
Makes sense
I appreciate you telling me.
Basically it's outdated
in Unity anyways
It'll stick around for a while, because Unity 7 is still ages away, and Unity 6 will have a long life, but as UITK is the future and has been a great replacement for debug menus for many generational releases now, I would avoid it
Essentially doing a test run of a menu similar to sims
or other games with the ~ debug menu
Having an issue with my custom terrain editor where if I try to sculpt multiple cells across two chunks borders, the cells at the borders of each chunk will be higher than they should (see gif).
I think this happens because I have code to prevent the borders of adjacent chunks from having gaps due to height differences which causes the cells at the borders to be updated multipel times in the situation in the gif.
The sculpt tool sets the heights of cells like this:
foreach (var cell in selectedCells) //selectedCells is a dictionary with a key/value pair of cellPos, chunkPos
{
//Get the chunk
MarchingSquaresChunk chunk = t.chunks[cell.Value];
//Cell index in the heightmap array
int idx = chunk.getIndex(cell.Key.y, cell.Key.x);
float newHeight = chunk.heightMap[idx] + dragHeight; //drag height is the amount of pixels the mouse has moved up or down
t.SetHeight(cell.Value, cell.Key.x, cell.Key.y, newHeight);
}
and SetHeight looks like this:
public void SetHeight(Vector2Int chunk, float cx, float cz, float height)
{
MarchingSquaresChunk c = chunks[chunk];
c.drawHeight((int)cx, (int)cz, height);
//Do we have a chunk to the left and are we setting a cell on the left edge?
var chunkLeft = chunks.TryGetValue(new Vector2Int(chunk.x - 1, chunk.y), out var leftChunk) && cx == 0;
if (chunkLeft)
if (leftChunk.heightMap[leftChunk.getIndex((int)cz, dimensions.x - 1)] != height)
SetHeight(new Vector2Int(chunk.x - 1, chunk.y), dimensions.x - 1, cz, height);
var chunkRight = chunks.TryGetValue(new Vector2Int(chunk.x + 1, chunk.y), out var rightChunk) && cx == dimensions.x - 1;
if (chunkRight)
if (rightChunk.heightMap[rightChunk.getIndex((int)cz, 0)] != height)
SetHeight(new Vector2Int(chunk.x + 1, chunk.y), 0, cz, height);
var chunkUp = chunks.TryGetValue(new Vector2Int(chunk.x, chunk.y + 1), out var upChunk) && cz == dimensions.z - 1;
if (chunkUp)
if (upChunk.heightMap[upChunk.getIndex(0, (int)cx)] != height)
SetHeight(new Vector2Int(chunk.x, chunk.y + 1), cx, 0, height);
var chunkDown = chunks.TryGetValue(new Vector2Int(chunk.x, chunk.y - 1), out var downChunk) && cz == 0;
if (chunkDown)
if (downChunk.heightMap[downChunk.getIndex(dimensions.z - 1, (int)cx)] != height)
SetHeight(new Vector2Int(chunk.x, chunk.y - 1), cx, dimensions.z - 1, height);
}
Does anyone see any logic issues which might be causing the behaviour in the gif?
The double layering at the split?
yes