#💻┃code-beginner
1 messages · Page 237 of 1
im having a problem on where im trying to combine daves and danis grappling hook + Affax grappling hook rope animation into one grappling hook with 2 modes and a nice rope animation but im having problems and i really dont know how to fix them
https://paste.ofcode.org/3c3q8YExriic7YYhdyqKSJ2 playermovment script
https://paste.ofcode.org/vDh7SC3HHbav4Y7YAejMJn grappling hook script
https://paste.ofcode.org/xmFxDn4MdkEHaYBKmFSD4r grappling hook rope animation script
also the errors im getting:
also the vids if needed
https://youtu.be/8nENcDnxeVE?si=nysbKGRLDhhZ5znC
https://youtu.be/TYzZsBl3OI0?si=ccS5LW06_U3qEYQ_
https://youtu.be/Xgh4v1w5DxU?si=_2xBejyRBzpf5wX5
🧷 Spring Script Paste
► https://pastebin.com/4ZkbS9cw
📦 Project Files:
► https://github.com/affaxltd/rope-tutorial
► Dani: https://www.youtube.com/channel/UCIabPXjvT5BVTxRDPCBBOOQ
► DaniTutorials: https://www.youtube.com/channel/UCn7E5qFz-BML6o7XnjtlytA
Hi, my name is Affax and I'm from Finland!
I'm an independent game developer who loves to ...
ADVANCED GRAPPLING HOOK in 11 MINUTES - Unity Tutorial
In this video I'm going to show you how to create a precise grappling hook / grappling gun ability that you can use in any first or third person game! The ability is flexible, and can easily be used in combination with a swinging ability to provide lots of air control!
If this tutorial has...
hey you slobs heres how to make a grappling gun
➤ WISHLST KARLSON - https://store.steampowered.com/app/12...
➤ Code - https://github.com/DaniDevy/FPS_Movement_Rigidbody
➤ Discord - https://discord.gg/P53pFtR
➤ Twitter - https://twitter.com/DaniDevYT
➤ Reddit - https://www.reddit.com/r/DaniDev/
➤ Facebook - https://www.facebook.com/danimilkman
➤...
please someone help , im losing my mind ngl
First error: You're creating a monobehaviour with new. You can't do that. Look at the line the error is on and don't create a component with new
Second: pm is null
Third: You're attempting to set the position of a point on the linerenderer that doesn't exist
Somewhat unrelated tangent: I don't particularly like tutorials such as these where the guy is just saying "ok, so this is a little too complex to explain but just copy this"
[pastes the entire source code of Minecraft]
This just leads to situation where you are unable to fix anything yourself
I've been there
(It's because they don't understand it and attempting to explain it would reveal that fact)
Yup

idk why , i dont like that as well , i like it when they explain lol
Basically you should be on top of this pyramid to know you've really learned something
I'm like in the middle somewhere
first error seems like if removing the new will make the Sping() red underlined but in the guys vid seems like it was working fine
second error i fixed it with just findingthe gameobject tagged with player and getting the player movement script
third error i really dont know how to fix it ngl even tho the line renderer exists
but in the guys vid seems like it was working fine
well, we haven't seen what he did
you'll need to show us
You can't just remove the new. You cannot create an instance of a complonent like that. The only way to create one is to add it to an object
The line renderer exists, but does the point you are trying to set
If you're trying to set the third position of a line renderer with two points in it that's going to be an error
so i should put where the position size to 3 and not 2?
You need to make sure that when you're setting a position of a line renderer, it has at least that many points in it
You'll need to check the error to find out which script and what line its on
because the screenshot did not provide any context
they are over here and the script is the grappling script
Do you have to declare override in the header for c#?
I see people writing stuff like public static override method
that's not a header
that's the method definition
Which one has the error? How many points does your line renderer have in it to start?
also static override are never together
Yeah
both of them have an error and it has 3
0, 1 , 2
but yes if you want to override a method you have to write override, and also the method you are overriding must be virtual or abstract
I’ve never heard of virtual before?
its the other half of override
well, the virtual keyword (along with abstract) is mandatory for using override!
any abstract method is implicitly virtual
lets you mark a method as being overridable on the extending class
and override is only used when your parent class defines a virtual method
what do you mean
because they learned from the mistakes of Java where things were just done implicitly and it caused errors
C++ has very similar rules, its just divided between header and source file
where C# only has source files
C# methods are non-virtual by default.
also rather declare virtual, then have to declare final like java
Yeah makes sense actually
Add this line before each of those:
Debug.Log($"Line Renderer {lr.gameObject.name} has {lr.positionCount} points");
You don’t have to declare final in Java dk you?
yes to prevent overrides you do have to declare final in java
If you want the default behavior of C# in Java you have to use final
Oh
oh-
I have a separate question. Let’s say you have a bunch of methods that will only ever be called in one class, but for the sake of organization you want them to all be declared separately in some different area. Would you use a separate class, class hierarchy, etc?
Defined*
would just make them private methods of the class they are called in
I would say stop wanting that and just put them in the class they're used in
worst case make regions or just visually organize the code
how can i make the grapple gun have 2 or 3 points
Add 2 or 3 points to the line renderer in the inspector
Yeah but if I have an already complicated class handling something like CPSR I’d prefer a separate area to have all the server checks I want to do on the received info
if you classes are getting that big and comlicated maybe its doing too many things
and should be multiple purpose build classes or components
It’s not big just complicated
then whats the problem
like this?
just clump them all togeather in the class that uses them then
I iust feel like it’s bad practice but I guess not
Yes
would say you are over thinking it, just solve the problem that needs to be solved and move on to the next task
feel creating a heiarhcy of classes just to separate out some methods that are call called in the same place anyways is more messy then just tossing them in where they are used and hides intent more
at one point, I had a class that was easily over a thousand lines long that did everything for my game's main enemy
I decided the solution was to use partial classes, splitting the class definition across five files
It was awful. I could never find anything.
it still says i have 0 points
@swift crag feel in that case i would use composition
Bingo
Then you likely have code emptying the list
and the error still appears
I rewrote the entire game to be composition-based
Back when I started my movement code files were 2k lines
everything is now an Entity with a Brain and Locomotion and Modules
Or the one you changed isn't the one you're referencing in the code
Entity.cs is still 700 lines long, but it's just bookkeeping for the other systems (and a bunch of debug visualization code)
also composition does not always mean components, it can be as simple as your MB instantiating a few regular C# classes to do other things within
bonus: i can now play as any entity in my game
the original player, the enemy
a light switch
it is lol
composition to me means to just declare the variables even if you're not goingto use em
yeah -- I went with MonoBehaviours everywhere so that I could serialize references
the only thing im worried is on how do i make the rope have the animation since i have this in the grappling hook rope animation scriot
like a character in my game, has a ton of components, that way stuff like managing its appearance, pathfinding, aniamtion, stats, avatar rendering in ui etc selecting what behaviours to run are all different components,
Well, according to your log, the length of the list is 0, so at the time the code runs, there are zero points. Either you're setting the wrong one or it's becoming zero after starting the program
Ok just let me paint this picture cause I feel like it really makes sense to have separate classes: I have a couple classes responsible for managing network time and sending, receiving, and verifying network states. (It’s just standard client prediction ). Instead of having a bunch of anti cheat checks all thrown into the class responsible for verifying, receiving, and sending states, why not have a separate class with flyCheck(), speedCheck(), combatCheck() etc…
im looking through the script and i dont see anything that clears the length of the list
well what i said eariler was one class if its for 1 purpose, but that 1 class should not be handling many many different types of things
i maybe be blind cause i dont see it so idek
like tend to have 1 class one purpose
Wow I managed to send my objects to the shadowrealm
Ik the sending receiving and verifying states sounds like a lot but just picture this class is like the overhead that manages these things
Look for anywhere you set positionCount or call SetPositions with an empty list
It’s only 200 lines
like a character at work, has 6 components, and maybe 10 or so regular C# objects in it for managing other things
if I have a prefabe with a serialize value which needs a script why can´t I assign it in the editor?
the seperation has nothing to do with how much code, its with purpose and what depednencies are needed at what time
Vector3 dampingFactor2 = new Vector3(
Mathf.Max(0, 1 - Damping2 * Time.fixedDeltaTime),
Mathf.Max(0, 1 - Damping2 * Time.fixedDeltaTime),
Mathf.Max(0, 1 - Damping2 * Time.fixedDeltaTime)
);
Quaternion CamDir = cameraTransform.transform.rotation;
Quaternion gunDir = gameObject.transform.rotation;
Vector3 acceleration2 = (((CamDir.eulerAngles - gunDir.eulerAngles) * Stiffness2) - Vector3.Scale(currentVelocity2, dampingFactor2)) * Time.fixedDeltaTime;
currentVelocity2 = Vector3.Scale(currentVelocity2, dampingFactor2) + acceleration2;
currentPos2 += currentVelocity2 * Time.fixedDeltaTime;
gameObject.transform.eulerAngles = currentPos2;
having a problem with rotations, if i could get some help?
i found this in the draw rope func of the grappling hook rope animation script
So, chances are it's getting set to 0 when you don't expect it to be
i also found this still in the DrawRope func
oh damn , do i remove the if lr positioncount == 0 then set it to 0?
I cant any script assign to the Slider
You should consider when you want to change it and why
What are you trying to drag in there
Which object
a slider which is in the actual scene
This appears to be a prefab. Prefabs cannot reference objects in scenes
The prefab can exist anywhere. The scene object only exists in that specific scene
you'll need to set it after spawning in an instance of this prefab
With =, usually
but how should I reference that object?
Instantiate returns a reference to the thing it creates
what? sorry i dont understand
maybe change the position count to 2 here?
https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
It returns the object it just created. You can use that reference to set whatever you want on the new object
That would make the error go away, but maybe you should consider the rest of your logic and see why it isn't already at 2?
Something no longer having errors doesn't mean it's actually working as intended
im thinking but my brain fried , idk anymore
ikik
but I instantiate an empty object which englobes all of this gameobjects
but this little objects are the ones I need to pass teh script onto
Then instead of doing that, put a script on the object that you can use to reference the other components in the prefab
also the error doesnt go away
cant i use the drawrope func so the rope has the nice animation?
what?
Make a script on the main prefab object that has the references you want
then, you can spawn the prefab with that script and use the returned reference to it to get the other objects you need
but should I create a new script with references?
tried it , doesnt seem to work sadly
but how do I pass them to the script in the object that is inside the prefab?
Those you can just drag in
A prefab can easily reference other things inside of itself
Should I make an entirely new script which only has references?
daves and danis grappling hooks are a bit diff , danis uses joints but daves uses raycast. maybe is that a problem ig? idk i hope someone can help me with this problem
yes -- it's a good idea to do this instead of doing a ton of GetComponent/Find/etc. hackery
Maybe instead of frankensteining code from unrelated systems, you should absorb the how of all of these videos and come up with your own method
I could try but I'm too dumb too make my own method
so how on earth do you hope to be able to smash together multiple slight variations of the same idea
Then you're definitely not ready to be debugging a hodgepodge of three people's disparate methods
At the very least, pick one and stick to it
What are all these errors?
(and if you did, did you just change capitalization?)
because you're still trying to reference a scene object from a prefab
Because either you changed the type of the object that field referred to, or your prefab is trying to reference a scene object
by doing what digi suggested
Okay so I think I should explain all the context
public class SomePrefab : MonoBehaviour {
public ThingToConfigure configureMe;
}
...
SomePrefab instance = Instantiate(prefab);
instance.configureMe.someField = somethingElse;
That is usually a good thing to do when starting to ask a question
The object spawning the prefab should get a reference to a script on that prefab. That script should have a reference to the object you want to set the slider on. The thing that spawned the prefab should then set the slider on that variable
You mean disperate?
Damn I guess that's for the better for a beginner 
No, I mean disparate
it's spelled with an "a"
I am generating rooms with empty objects which group different gameobjects which depend on others objects by references
Welp there goes my cool idea of having a grappling gun with two modes
but how should i get the reference if it is not by the editor
"which depend on other objects by references" is extremely vague
Instantiate returns a reference to the object it made
so all I can do is say to do this
Use that reference to get access to the other things in the prefab
and set the variables on them
it is an object that needs the compoinent in a slider which is in the UI
Where can I find the Unity tutorial, is there a level?
Okay, so whoever instantiates the prefab needs to have a reference to that slider.
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
how
thanks brother
by existing in the scene from the start
if it doesn't exist in the scene from the start, then someone needs to give it a reference
how can I share this unity game file with a friend on discord for example?
it does
Send it
zip up the "Super Capsule" folder and send it
Just the .exe application?
it exists in the scene from the start
No. The entire folder.
No the whole folder
Okay, so give it a field that can hold a slider
and assign the reference in the inspector
I have to zip it first though right?
Of course you can.
So then have that object reference the slider you want. Then, when you spawn the thing, set that thing's slider variable to the one the spawner has
It's part of the scene.
why not
look
Don't show a tiny cropped picture
Show the whole editor
you just said they're both in the scene at the start. Why can you not just drag it in
What does this have to do with anything
the only thing in the scene at start
is the sldier
This is not what we are talking about
the room generats in the Awake
so then why did you say the thing spawning the prefabs was in the scene at the start
we cannot help you if you outright lie about what is happening
Then who creates the rooms?
A gameManager in the awake
Something must exist in the scene to instantiate the prefabs.
Okay, great. Give the GameManager a reference to the slider.
Cool, we're getting somewhere. Does that object exist in the scene before the game begins
They have to have Unity? Otherwise I can't send them a playable game file?
Send the whole folder
Okay, I have it
everything in your screenshot
No they don't have to have Unity.
zip the "Super Capsule" folder. send that.
Now, when the GameManager spawns the prefab, set the slider variable on that prefab to the one you've just dragged in
And how do I "pass" that reference
=
but is there a way to access to that specific object inside of the prefab
Yes, by doing the thing we explained a while ago where you make a script and drag in the references
that you said you did
the references are dragged
Make a script, put it on the base object of the prefab, and drag in the things you want
did you read the code that I wrote
yeah but i do no tunderstand it
then ask questions about it instead of just silently ignoring it
what part of that code do you not understand?
Evenin' all.
So I have a 'quadsphere' and some XML that I need to translate into a Shader (Not a shader question lol). The xml includes Lat/Long coordinates, would anyone have any idea (or be able to point me towards a resource) that would let me figure out how to apply/assign long/lat coordinates to my quadsphere? (not sure if I made any sense with that. lol.)
I can't tell if you're asking how to work with your QuadSphere data structure or API or if you're asking how to parse XML
XML shouldn't be involved in the quadsphere part
presumably you parse the data and then move on
The quadsphere is a model, no coding involved. 1 sec.
if the sphere's UVs are just a rectangular unwrapping, it should be trivial to go from coordinates to UVs
just remap latitude and longitude into the 0..1 ranges
It's made up of 6 'faces' and then manipulated in my modeller to spherise it. So it has 6 'flat' UV's
!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.
Parsing the XML isn't an issue, I know how to do that (xml structure below)
<Rule>
<Layers>
<Layer Material="OceanIce" Depth="20" />
</Layers>
<Height Min="0.0" Max="0.43" />
<Latitude Min="0" Max="90" />
<Slope Min="0" Max="1" />
</Rule>
It's more trying to figure out how to make use of the Latitude (assigning values to the QuadSphere)
Sorry man, not sure what you're asking.
Not understanding what you mean then sorry.
how is your sphere UV mapped?
assuming that you're trying to do something involving textures or the sphere's material
if not, i need to know what "assigning values" means
6 faces (top, bottom, front, back, left, right). And yeah, the image I posted above is the sphere mapped with heightmaps for each face. I'll be creating a shader to colour the 'planet' based on the XML values and the heightmap.
okay, so you need to write data into a texture
you need a method to convert from lat-lon to UV coordinates
I don't know how you would do that off the top of my head
Yeah, teh height and slope I can figure out how to parse/apply, it's the longitude value that I'm not sure about.
I guess you could shoot a raycast at the sphere and get the UV coordinates from the hit.
does someone know how i can use the same key to change modes of the grappling hook? since rn im using F for swinging mode and G for normal mode and i wanna just use F , does someone know?
instead of just setting the mode, check which mode you're in and set the other one
if (mode == Mode.Swinging) {
mode = Mode.Normal;
}
e.g.
could also use a state machine. input f = change mode. for each mode define the action taken by change mode
Hey, probably a beginner's mistake, but I'm having trouble with some errors. For a bit of context, this is my first 2D game where, for now, you can only move around, collect some points. I'm trying to add enemies, but those 2 errors comes up. I also sent the LogicScript, and the 2 scripts of points and enemies. Anyone knows where it comes from ?
Duplicate script
You can't declare two classes with the same name.
even the Start ? So how can I make it ?
Don't make two classes with the same name
Start is not a class.
Start is a method.
target1script is a class.
With some trial and error
I am having a problem with unity's EventSystem. I have an element I want to re-select immediately after deselecting it. It's a text input field.
After onSubmit is called, I've tried to reselect the field but it keeps not getting reselected.
eventSystem.SetSelectedGameObject(gameObject); is what I am calling to try to select it.
I've tried calling this:
- immediately after onSubmit is called
- on Update
- on LateUpdate
- the next frame through a co-routine
but every time the field gets deselected because the field calls "DeactivateInputField" on itself for some reason
why does this error appear
Whats the correct way to reselect it? Its a text field element. I want it to act like any text field a chat engine uses like when I hit enter on my keyboard right now here on discord, the field remains selected and further keypresses continue to fill this field
!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.
Like it says, you're trying to use an instance reference to access something that should be using the type name
Also I'm assuming this is an enum, in which case that line makes no sense at all
I would expect something like:
if (currentMode == ChangeGrapplingModes.Swinging)```
I'm making a dash machine for my game and right now. My character only moves to the right and doesn't do the same to the left. No matter what it will head left. Does anyone know why?
Try it in what way?
I am not sure how to try it in this context. Its also important that it be possible to deselect it when selecting something else, I don't want to foricibly always have it be selected, I want it to be only be selected when the user calls OnSubmit on it, not just on any deselect event
move right or dashes right?
Dashes right
oh dammit im dumb , didnt check my player movement statehandler lol
is the Flip code ever happening? Is the scale getting inverted?
AH, I forgot to call it.....
I'd use IDeselectHandler and check if the user just submitted
(IDeselectHandler requires you to implement OnDeselect, so this is roughly what Hambones suggested)
trying this now, if it also fails Ill try implementing that handling
also consider
this will tell you if you're already attempting to set a selected game object
I'm not sure if that will be true whilst OnDeselect is running as the text field unselects itself
hey guys, i need help with using play asset delivery.
normally my game is consisted of 3 scenes, but its size was somewhere around 1gb, so for me to upload it on google play store i need it to be less than 200 mb, for that i decided on using play asset delivery, i have this code right here that is supposed to download the asset bundles and then have 3 different functions for loading the 3 scenes, is it correct ? and if it is how should i do the build and how am i supposed to try it ?
https://gdl.space/soriqihawu.cpp
Oh that will be useful
{
if (reSelectOnSubmit)
{
eventSystem.SetSelectedGameObject(gameObject);
reSelectOnSubmit = false;
}
}```
also forgot to add the i\f statement so that it doesnt always reselect
It didnt infinite, it just didnt reselect 🤔
or if you guys dont know, is there anywhere i can get help with uploading my game on google play store? that would be appreciated
I feel like I must be missing something because I cannot get it to reselect ever, not on update, late update, co-routine next frame
did it call reselctonsubmit?
ReselectOnSubmit never got called, debug texted just now
scratch that, it does get called but not when expected
but it also doesnt work
try implementing IDeselectHandler in your script
it doesnt get called OnSubmit, but it does get called when I click off of it, and even though the bool evalulates true, " eventSystem.SetSelectedGameObject(gameObject);" this simply doesnt work
put it on the input field and define OnDeselect in the way you did "reselctonsubmit"
I think the problem is that eventSystem.SetSelectedGameObject(gameObject); is not how you select something in the event system
Ill try that handler next but if it still doesnt work I think that is the problem, because calling that line thusfar never selects no matter where/when it gets called
ill try changing it from gameObject to a more explicit reference to itself maybe?
that should work fine - depends which object you're passing in there though
If it doesn't have a Selectable on it, that might be a problem
ah, so it just errors on you if you try to do that!
good to know; i was a bit curious about that
changing it from gameObject to a reference to (myThing.gameObject) gave that error
before no error at all which wasnt useful
I guess it just silently ignored your object that didn't have a Selectable on it
ah yeah it didnt
I'd set a field when you submit and when you deselect
If you deselect after you submit, then reselect in Update
my code is being run in the script but hooking into the input field
I bet the deselect happens in the same frame as the submit
in that case, you'd just check if both happened, then reset both bools to false
Ill try this now, since it didnt work before on update but maybe I was selecting the wrong thing, there was no error before
I kind of wish selection worked on a Selectable, rather than a GameObject
I guess it could be ambiguous with multiple selectables on one game object
honestly unity is nice in a lot of ways but ugui is a huge pita. i feel like i learned it a couple year ago and then somehow lost all knowledge...
i remember having an epiphany about anchors and positions and whatever and i have no idea how it works anymore
this DOES get called, but it doesnt select the field, and it doesnt give an error
and when I try to step into it, I cant for some reason
hi! how can i enable baked navmesh in editor view?
probably your gizmos in the top right corner there is off
just out of curiosity where is this eventSystem reference coming from?
Inspector, its a dragged in reference to the scene EventSystem in the scene
I think I've already turned it on.
Maybe my understanding of 'selected' is whats flawed here
i kind of doubt it
This is what I am trying to achieve without needing to reclick the field each time
I assumed that the input state that recieves inputs would be selected but I never tested that assumption and am not sure how to 🤔
Hmm, not too sure then as I've not used unity's navmesh tools for a while, but I do remember running into a similar problem.
the most braindead way to test this would be to put csif(input.getkeydown 'whatever') Debug.Log(thisthing.selected);
you can probably also have a debug textbox that just periodically polls whatever values you're interested in
Dont they match?
Right sorry what I meant was how do I check if that blinky line input state is being selected
I can debug log the event system and I can see if the field is selected, which is True, but its not in the blinky line input state
but i think you'll find that indeed, a textfield IS selected when you are inputting it
Yep
I have a public int itemType; in the interactable code (to set as 1, 2 or 3), but it cant seem to relate with the dictionary in interactor or how to approach it rotationDictionary.Add(1, new Vector3(-30, 0, 0)); rotationDictionary.Add(1, new Vector3(-30, 0, 0)); rotationDictionary.Add(2, new Vector3(20, 0, 0)); rotationDictionary.Add(3, new Vector3(0, -10, 0)); I added a private Dictionary<int, Vector3> rotationDictionary = new Dictionary<int, Vector3>(); before void start, but i dont know how to make it work @-@ or if this is ok in update inside raycast but im not sure foreach (var kvp in rotationDictionary) { if (kvp.Key == itemType) { Vector3 rotationValue = kvp.Value; interactable.transform.Rotate(rotationValue); foundRotation = false; } }
um... blinky line input field?
hm maybe I have to call something on the inputfield to set it to the blinky line up
I mean like any text field when you are able to type the bar blinks
even here in discord
which Im starting to think is a state separate to just being selected
I remember running into that issue and I think how I fixed it was just not use select/deselect
and just appended directly to the text via input events
"inputField.ActivateInputField();"
this exists, ill try calling this
Yep that was it. I had to call ActivateInputField, not just selected
🫠
the issue in the end was my assumption that being selected = input field active
ugui 
more just tmpro having 10000 methods
I cant think of a use case where I'd want the field selected but not edit active, but I am sure someone somewhere needs it that way
Sweet I can move forward now at least, thanks for helping me debug 👍
my word game I dont ever need to select/deselect it (should always be active) so my hacky way works for my requirements
that was more duck debugging as you solved the problem yourself
i am not sure why the hell my character is still hanging in the air when the rope is gone , this only happens with the normal mode of the grappler
let me get a vid rq
i really dont know why this happens lol
does anyone know how to make random terrain generation? iam trying something, it kinda works but iam not getting the final thing i want, iam currently working at school project, i chose Survival game so iam trying to make great random generation
why is it when i call my static bool on my cameras zoom script, that it only zooms a little bit?
https://gdl.space/yavamatifo.cpp (i dont care that its messy i just slapped it together)
seems like this is the block of code that makes that problem
What to you mean by "when i call my static bool"?
Think about it:
if (isZoomed == true || interactZoom == true)
{
GetComponent<Camera>().fieldOfView = Mathf.Lerp(GetComponent<Camera>().fieldOfView, zoom, Time.deltaTime * smooth);
}
if (isZoomed == false)
{
GetComponent<Camera>().fieldOfView = Mathf.Lerp(GetComponent<Camera>().fieldOfView, normal, Time.deltaTime * smooth);
}```
What happens when interactZoom is true, but isZoomed is false? Both of these blocks will run each frame.
I have a gravity direction, a vector3 of magnitude 1. and I'm wondering how to calculate the global direction of my movement which is a vector2. for a second I thought I just had to multiply but that sounds wrong. for instance if my movement is (0,1) so w is pressed and it should move forward and when gravity is (0,-1,0) so down. it needs to somehow apply a force of (1,-1,0) assuming no rotation and a g of 1. but when the gravity direction is (0,0,-1) the movement would be globally down so it'd need to be (0,-1,-1)... I think. I don't get this
If interactZoom is true and isZoomed is false both lerps run
does anyone know why this happens?
i don't understand the relationship between gravity and what direction your w key should move you in. Can you explain how your game is supposed to work? Normally the two are not related.
i need help, now it looks like its working, but i dont think this is usable as terrain for world
unless you need predetermined trajectory, usually gravity just acts on the objects independently throughout your update loops
looks like water lol
hello, do you know why this doesn't work ?
https://hatebin.com/chlfhnlyku script where inventory is defined
https://hatebin.com/nyiwwzmhob script failed to load it (screenshot is from this one)
thanks in advance ^^
i dont know how to make it look like terrain, iam not going outside to see world that much T_T
I want to have more control over my player's gravity and thus, if I change its gravity and rotation to walk on a sphere for instance, I need to set the player's gravity direction towards the center of the sphere. then to walk forward I need to change the direction based on which way gravity is right?
i would spread the noise a bit more
just play with the noise for an hour or two
I don't know - what does "forward" mean?
I would think forward is either the direction your camera is facing or the direction your player is facing
Is this a 3d game?
yes
man i dont even know how i made this, i just yeeted random equasions that made something like this
If that screenshot is the line the error is on, then inventory is null
inventory is null
So you're walking on the surface of the sphere? Basically forward should either be the direction your player is facing, or your camera, or along the tangent of the surface you're standing on
you need to decide which
do you mean UpgradesInventory ?
adding a layer of texture sampling for the noise is my goto solution to add some variance
public NEWSCRIPT inventory; in ProductionUpgrades
that's why we said inventory
ill try that, idk how to do it but i will try
also whats up with NEWSCRIPT as a name lol
oh yes ok thanks
Welcome to this series on procedural landmass generation. In this introduction we talk a bit about noise, and how we can layer it to achieve more natural looking terrain.
A quick summary:
'Octaves' refer to the individual layers of noise.
'Lacunarity' controls the increase in frequency of each octave.
'Persistence' controls the decrease in ampl...
I'm just wondering how you calculate this. an uneducated guess was a matrix transformation but I wouldn't really know :I
calculate what
which part?
i watched this, but it got too complicated for me, but thanks
now its doing this , its too flat
honestly pretty straight forward video, abit long, but it's as detailed as you're getting
honestly the best videos on this subject is def the ones from Sebastian
ok thanks, imma watch it again
can replace the noise map generator and grab fastnoise package and use that instead
you get your camera (or something) forward, project on plane with normal being your up (that's minus gravity direction), then normalize - that's your sphere tangent forward... then you cross that with up and that's your right... then you multiply the horizontal input with the right and the forward input with the forward and that's your direction... and then there's the down which you add to that vector for gravity
i have to make something impressive for that project, yeah i wanted to do that, but teacher said NUH UH
the input part of my movement vector.
so I have gravity which is simply multiplying the g value with the direction of gravity.
the input from the player and I combine these vectors to get the global velocity I should set rb.velocity to
Again it depends on which of the things I mentioned you want
I mentioned three possibilities
I guess the direction the player is facing
cuz it's a third person game
movement is very important for this project so I'm just trying to understand and learn to get it right
so how can i access this correctly please ? still don't work (i may be dumb)
I'm just a bit overwhelmed trying to do math I have no experience with xD
direction player is facing sounds weird... unless by that we mean camera direction... if you're looking at the player from the side and press W, where does the player go? where the camera is looking or where the player is looking?
(do you have control over camera?)
did you assign inventory in the inspector?
also why do you have two scripts do the same JSON utility saving
no but i can't put anything in the field
if you can't add NEWSCRIPT in the field for inventory then one of them is a prefab and another belongs in scene ?
only one need to do it it was for a test
they are form different scenes
yes. but I guess it makes sense that when you are looking at the character from the front, w should rotate them 180 degrees and make them walk away.
I guess I do want camera direction
i don't think anyone is a prefab
and then I assume you don't want to actually try to go down through the "curved plane" that is the surface?
you cannot reference between scenes
yes? sorry I might be in over my head xD
then how can i do it ? it was the purpose for me to use json
character controllers are pretty tricky, yeah 😛 but! back to my initial reply to you 👆
i tried to use json to access data across scenes
what does json have to do between 2 scripts referencing each other
idk how to do another way
can somebody help me with this error code?
Animator.speed can only be negative when Animator recorder is enabled. Animator.recorderMode != AnimatorRecorderMode.Offline
UnityEngine.StackTraceUtility:ExtractStackTrace ()
ElevatorDoors:YouAreChosen () (at Assets/scripts/ElevatorDoors.cs:19)
UnityEngine.GameObject:SendMessage (string,UnityEngine.SendMessageOptions)
PlayerInteract:Update () (at Assets/scripts/PlayerInteract.cs:18)
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
If you want to preserve data between scenes why not just make a Singleton with a DDOL
ElevatorDoors:YouAreChosen sets animator.speed to a negative number. That's not supported.
and which one is line 19 ? since you omitted the namespaces
19 line is _Animator.speed = _f;
and i want it to be - since i want to play it backwards
ah yes like Pulni pointed out, negative animator speed is not supported
Negative playback speed is only supported when the recorder is enabled. For more details refer to Animator.recorderMode.
i think you can just invert the animationClip/state speed itself no ?
Note that individual animation states can still run backwards
You just can't play the entire animator backwards
This would require it to actually run transitions backwards, which it can't do
lazy animator... 😝
I just duplicate the clip and put with -1 speed and call it a day lol
Then it's basically:
Vector3 forward = Vector3.ProjectOnPlane(cameraForward, surfaceNormal);```
if you want a Quaternion (which you can use to transform your input vector you can do:
Quaternion rot = Quaternion.LookRotation(forwrad, surfaceNormal);
Vector3 rotatedInputDir = rot * inputDir;```
if I'm not on a specific object but simply gravity is set to something other than down, can I just use that vector, multiply by -1 and input that instead of surfaceNormal?
yes
Is it better todo that with a json or Xml file ?
private void LoadDialogues()
{
string path = Path.Combine(Application.streamingAssetsPath, "Dialogues.json");
Debug.Log("Pfad zur JSON-Datei: " + path);
if (File.Exists(path))
{
string jsonString = File.ReadAllText(path);
JSONObject dialogJson = JSON.Parse(jsonString).AsObject;
foreach (var key in dialogJson.Keys)
{
JSONArray dialogArray = dialogJson[key].AsArray;
string[] dialogLines = new string[dialogArray.Count];
for (int i = 0; i < dialogArray.Count; i++)
{
dialogLines[i] = dialogArray[i].Value;
}
dialogues.Add(key, dialogLines);
}
}
else
{
Debug.LogError("Dialog JSON datei nicht gefunden " + path);
}
}
Is it better to do what? Parse JSON? I would never try to parse an XML file as JSON
i wish they just named it Rotation
yeah and made the internals private
you don't have to think about matrix algebra or quaternion arithmetic
you just use the Vector3 and Quaternion methods
no im mean in general what is better
JSON IMO, it's simpler and faster.
tbh I have no clue how to make or read a quaternion. I just know they magically do rotation stuff xD
you don't need to read it
my knowledge on them ends at them being a vector4
you make it through the static methods here:
https://docs.unity3d.com/ScriptReference/Quaternion.html
all they are is a variable that holds a rotation
Okay thanks . i was confused about that a lot people in a forum mean that xml is better for performenced
don't worry about anything else
XML is known to be much slower to parse
e.g. Quaternion.AngleAxis(45, Vector3.up) gives you a rotation 45 degrees around the vertical axis
(clockwise around it)
my opinion ;D thanks
oh so it's just a directional vector with 1 more float for axial rotation?
no
don't worry about how it's represented internally
that's just one way to make one
look at all the functions in there
there are many ways to craft them
How should I make it so my character go dash up, down, up the right, up to the left, etc?
I found a solution to the problem with overlapping events in the blend tree:
I found another solution to the issue with overlapping sounds when using blend trees which is to use the blend weights. The function that the animation event calls can take one parameter, which can be the animation event itself, so you can pass it into the step function and access the blend weights from there to get the audio to only play when it crosses a threshold.
How do I pass the animation event as a parameter?
er, that doesn't show an example of it being received, though
you just accept AnimationEvent as the single parameter for your method
// For a value type action.
// (Vector2 is just an example; pick the value type that is the right
// one according to the bindings you have)
var v = action.ReadValue<Vector2>();
} I was wondering how you use this, I was confused by the documentation
would it be a tween sequence?
i'm unclear what you're confused about
given an input action, this reads a Vector2 from it
that's it
are you unsure how you'd get an InputAction in the first place?
you use it however you want. In this case v will be the current value of the action. What you do with that depends on what you're trying to do.
So my character can only dash left and right but I want more dirction like up and down. I also do wish you can go at angles and my game is 2D as well
Thank you!
what should I do for vector 2, should I keep it like that?
nice o: the difficult part for me is that due to the ideas I have for this game, there might be multiple gravitational forces working on an object xD so I need to calculate everything acting on an object and then set the rb.velocity to all of it combined xD gravity alone is already giving me trouble though xDDD
this question doesn't make any sense
if you want to read a vector2, then..read a vector2
That should be fine -- figure out how to calculate the force vector for one object
then you can just do that many times
Hello, I am working on some stuff for screen touch if I use IPointerDownHandler I can test with simulated touch screen but when I use input.TouchCount I cannot does anyone know how I can test input.TouchCount code on my PC?
don't think you can simulate multi-finger touch with PC
I could be wrong though
Tbh the code im using is just for one touch, its just that in my experience the touch count is never greater than 0 when I test on PC
tbh applying the force vector for something like a spell effect that simply sucks in stuff is super easy. just (objectPos - attractorPos).normalized * attractionForce. only the actual base gravity should give me trouble 
I got this
how do i trigger button click from code?
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class ButtonClickWithRaycast : MonoBehaviour
{
public Toggle toggleActive;
void Update()
{
// Check if Left Mouse Button is pressed
if (Input.GetMouseButtonDown(0))
{
// Create a ray from the mouse position
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
// Perform the raycast
if (Physics.Raycast(ray, out hit))
{
// Check if the raycast hits a UI element
if (hit.collider != null && hit.collider.GetComponent<Button>() != null)
{
// Press the button if it's clicked
ExecuteEvents.Execute(hit.collider.gameObject, new PointerEventData(EventSystem.current), ExecuteEvents.pointerClickHandler);
}
}
}
// Check if Left Shift key is held down
if (Input.GetKey(KeyCode.LeftShift))
{
// Activate the toggle
toggleActive.isOn = true;
}
else
{
// Deactivate the toggle
toggleActive.isOn = false;
}
}
}
what do you mean by "the button click"?
!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.
Can I be annoying and ask if theres an event system based handler i can use to do the same thing?
Haven't experimented too much on this yet. I typically connect my android to my PC to test
what happens when you click a UI button
Ok no worries ill just check for mouse clicks in the code too, thanks for your help
just make a function that does what you want.
Call that function from both the button and from your other code.
i have this many buttons.
Thanks for telling me how many buttons you have.
yeah, because its impossible bruh.
What's impossible?
adding the funtion like you said
it is not impossible by any means
oh
Also I don't understand this code. Why is it doing a physics raycast for UI elements
and you haven't explained under what circumstances you wish to call your function
because i am using XR input module for VR UI support but it doesent work in PC.
i have PC support because i get tired of putting on the vr headset and taking it off so mutch
but what's the question? You're trying to just support the buttons on PC?
yea
So why are you doing physics raycasts? What's wrong with the normal input module and event system stuff?
because vr is alreaddy there
You can add both
physics raycasts are never going to work for UI though
I wanted to ask if i am making a pathfinding enemy for a procedurally generated maze and I want to use A Star algorithm for the path finding whats the best way of doing this?
what do you mean by best way?
i need to change values of MapGenerator, but since i added this line of code it just shows this GENERATE BUTTON line" [CustomEditor(typeof (MapGenerator))]"
Write the algorithm and use it
is it something in setting?
you made a custom editor. It is drawing your custom editor. What's the issue?
I have but I've also been told to download assets and try it and i came to ask abt that
You need to call DrawDefaultEdtior or something, if you also want the default stuff
on that video he sees both the values and the button
Or just use NaughtyAttributes instead of writing a custom editor
https://dbrizov.github.io/na-docs/attributes/drawer_attributes/button.html
is this good?
you tell us 😛
i don't know
iam trying to do it like that video you sent, cuz iam totally confused what is he talking about
but this is what he ses
idk if its cuz its old video or cuz something is off in my settings
yes it's been explained to you twice now
oh didnt noticed
sorry
thanks
Hey, the error is Only server can spawn NetworkObjects
um you have to be the server host i think
Well okay, but how do I spawn a player from clicking a button?
You're just calling SpawnPlayerObjectServerRpc
thanks unity
if you're a client, you run the method
ah, no, I am incorrect: it should execute that on the server if it has the ServerRpc attribute
but since it calls SpawnPlayerObjectClientRpc, that's sending an RPC to...everyone
and they all then try to run SpawnPlayerObjectClientRpc
Yes but if they only run on the server the client doesnt get recognized
Its just a prefab
As host
do you have a graphic raycaster on the canvas? Do you have some other UI element blocking everything?
I have a Problem with collision detection, i want something to happen when colliding, but when my game Object(cube 3d) collides with a platform (long cube 3d) only on an edge, it doesnt detect a colission,why?
- How are you trying to detect a collision? Can you show the code?
- Can you show the inspectors for the two objects involved?
i think you need a rigidbody it always works for me
you can turn off use gravity
private void OnCollisionEnter(Collision collision)
make shure both the objects has isTrigger off.
- Show the full code
- show the inspectors of the objects please as I asked
if you want trigger turn trigger on on them and use OnTriggerEnter
wym with inspector
So you need to first put a Debug.Log at the very start of the OnCollisionEnter to make sure it's not actually running
because right now there's if statements etc
yea start debugging it
Debug.Log will save your life kid
that feels wierd for both of the objects
horizontal = LeftAction.ReadValue<Vector2>(1.0f, 0.0f); there is an error at ReadValue where it says that read value cannot take two inputs, how do I make it so that the parenthesis attatch to the vector2?
Why are you passing parameters into ReadValue?
Readvalue doesn't take any parameters
how do I make it so that the parenthesis attatch to the vector2
This doesn't make sense
wym with if?
if (...)
an if statement
your code is inside control things like that
add Debug.Log to your code to see which code is running and when
yes ok imma log it
and to print out values
what values? like collided
like the name of the object you collided with
alr
read the error message
What's the error say
you have a second error on baseStats.attack
this is probably messing up the method invocation
Does PlayerUnit have a function named TakeDamage
with this tween sequence i have setup the nail goes back into the wall no matter if i make the value for moving it a negative or positive number idk why
that was the error, thnx, i guess i just cant read error messages
You should probably start doing that
they're quite relevant
So I'm using a CinemachineVirtualCamera with the AIM setting to POV. now i see that when you use a freelookcamera there are properties you can access to disable and enable users mouse input to rotate the camera, for example -
public CinemachineFreeLook cameraLook;
cameraLook.m_YAxis.m_InputAxisName = "Mouse Y";
cameraLook.m_XAxis.m_InputAxisName = "Mouse X";
i see the properties in the CinemachineVirtualCamera script for the X and Y input axis names but i can't seem to figure out how to access them through code.
anybody know how to access those properties?
<@&502884371011731486> Scam link
If you can see them in the code but they aren't public then restrictions are in place and you might not be able to access them from your own code.
You'll know that when they won't appear in the completion list, and referring to them will produce the following error:
'XYZ' is inaccessible due to its protection level.
never mind i got it figured out. had to grab the POV component from the script i guess
CMvcam1.GetCinemachineComponent<CinemachinePOV>().m_VerticalAxis.m_InputAxisName = "";
CMvcam1.GetCinemachineComponent<CinemachinePOV>().m_HorizontalAxis.m_InputAxisName = "";
why wont my hammer move to the nail?
hammer script: https://gdl.space/ifibumabob.cpp
nail script: https://gdl.space/rukujamowu.cpp
why do you have so many static variables?
also ScrewInteract.nail has absolutely no relation to HammerInteract.nail
static 
for the mechanics
you're also starting so many DOLocalMoves since you start one per frame once that static bool is true
I don't see a reason for ANY of those to be static
that is not an explanation. nor does any of this need to be static
could you explain how the mechanics lead you to make those variables static
so you cant interact with the nail after you already interacted and stuff like that
guess i could just disable the script on it for that
what does that have to do with a variable being static
That is a poor reason, and makes it harder for you
yeah i dont know mate i was just using this to try and learn about sharing variables
i have a sneaking suspicion that they think making a variable static makes it have anything to do with some other variable of the same name and type on a different object that is also static (which of course it does not)
this is some cursed code. also it doesnt even look like these scripts are related or do anything to each other
static means something is tied to the definition of the class, and not to an instance
how do i fix it then lol
you start by learning how to [get a reference](#💻┃code-beginner message)
learn fundamentals before you try fixing something
you cannot fix what you do not understand
this is why i was trying to make this so i can understand
there is a LOT to fix, your best solution is honestly learning the basics first and then coming back to remake these scripts. this current way of coding is not fixable
ok
yeah, we’d just be teaching you the basics of the language, which you can learn from many different tutorials
i know most of the basics just this is confusing to me
not enough
static variables are a part of the basics
Referencing is one of the most basic things to know.
cheers
references are core to C#. this is something you need to know very well
ok sound
just as a summary for things to learn more about,
as others pointed out, the static variables are a problem. learn to get a reference to an exact object that you want. the link posted to you by others is a good resource
the scripts seemingly arent related (not sure if thats intentional) but i cant see where you even call half these methods.
comparing the name of an object is pretty bad/fragile obj.name == "Item_Hammer" . someone accidentally naming something the same name or accidentally changing the name of this object will break your game.
in the HammerInteract script, you are calling Animate every frame if nailInteracted is true. this looks like something you would only want to do once, when you set the value of nailInteracted.
Is there anyway to make my pixel perfect camera use less pixels to handle rotations? idk exactly how to explain it but i want the arrow to be more jagged
it has nothing to do with the image as it is 16x16
oof
its how the camera handles it
i dont think there is a way then
ive seen a lot of games do it
secondary camera without pixel perfect?
wdym
In the future #🖼️┃2d-tools
Render the arrows through the non-pixel perfect camera
Think im goofing with dicts, any reason why this wouldn't be setting the value in the dictionary? (this code is running and the value is int)
currentRound.activePlayersDictionary[winningPlayer] = currentRound.activePlayersDictionary[winningPlayer] + 1;
Have you tried logging the value after setting it to make sure the code is actually running
Is there a way to do?
public float DashCoolDown => _dashCooldown;
private readonly WaitForSeconds _dashCooldown = new(3f);
obvious type mismatch here, but there's no like .Seconds or anything.
only thing i could think of is a create another variable for the time as a const float, and pass that in to both.
public float DashCoolDown => time;
private const float time = 2f;
private readonly WaitForSeconds _dashCooldown = new(time);
meh guess so.
seems weird to need a const float here, since you wouldnt be able to change this value. You can just keep track of the value without const and then assign _dashCooldown in Awake/Start.
yeah but i want to access DashCoolDown elsewhere, but based on the _dashCoolDown time.
Which boils down to:
public float DashCoolDown { get; private set; }
private const float _dashCoolDownSeconds = 2f;
private readonly WaitForSeconds _dashCooldown = new(_dashCoolDownSeconds);
But lmk if you're seeing something I'm not 🤔
if DashCoolDown is only meant to expose _dashCoolDownSeconds, why not just make the latter public? it's const so it's not like something else can change it
its more like you want to access DashCoolDown and have _dashCooldown be based on the time
ah true, with the const, you're right.
oh weird, const is not exposed to other scripts though. huh
it's not an instance member, treat it like static
Guys what is Good tutorial on unity? And should I learn Roblox Lua first I'm split between Roblox or unity
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
For status effects do you create a class for each one combined with the usage of an interface or do you go with scriptable objects?
whynotboth
an SO for each effect which implements OnApply, OnTick handlers is a totally valid approach
for something as generic as statuses though it can be nice to have them be more like simple tags and handle the effects where they happen, depending on what kind of game you're making and how consistent your statuses will be
to me would depend if its more logic or more data driven
if more data, and just a bunch of numbers defined for each effect, or each category of effect SO's can be nice for saving those numbers
if they are all very different and require different logic, a interface to apply them and a new class that implements it for each one
yep, i generally avoid that SO approach because 'statuses' tend to be a generic enough concept that it might do all sorts of stuff from preventing actions to preventing death to granting an ability and coming up with a consistent api for all that isn't worth the trouble
yeah why i mentoned SO's for data driven or just a interface otherwise
Apply could take in a instance of the player and mutate it as it sees fit
definitly one of those systems where there's a few valid ways to go with pros and cons and what works for you really depends on what you're trying to do
I've liked using SerializeReference to define effects
public class StatusEffectDefinition : ScriptableObject {
[SerializeField] LocalizedString label;
[SerializeField, SerializeReference] List<Effect> effects;
}
where Effect is an abstract class
with methods like Apply(Entity target)
is serializereference good? i used odin from before it existed and haven't tried to switch over cause i don't know if there's any weird gotchas
The [SerializeField, is redundant
it has nothing to do with odin
i know, but before you could do it i used odin to accomplish what it does and so i still do that
but maybe i don't need to!
its just a way to reference plain old C# classes that are serializable
instead of the normal SerilaizeField where its a copy of the data
SerializeReference has no inspector for null values and that is one of the reasons why it's annoying
exactly the sort of information i was looking for
yeah generally needs custom ui
cant really have a inspector for null, since it does not know what shape the data is
And making a generic inspector that also supports property drawers and doesn't override the default editor is a pain in the ass, but I have a drawer that does it
since it accepts interface types as well as concret types
well, you can just have a selector of those subtypes, or a specified section of those subtypes
https://github.com/vertxxyz/Vertx.SerializeReferenceDropdown
I haven't touched my drawer in a while, but it's a huge pain in the ass
i do find SerializeReference to be ultra fragile though
few months ago had what should be a perfect usecase but it was too fragile to long term use
no guid for the type, so a refactor can break all the references
yeah i am very way of any of my game data being in a state where it will break if i rename a class or move a namespace
i've been traumatized and take that divide probably too seriously now
You can refactor the type fine using UnityEngine.Scripting.APIUpdating.MovedFromAttribute
odin has the same issues though
yeah but you have to remember to do that beforehand!
you can will co workers do that, prolly not
you can revert and then do it if you notice early enough
And Find and Replace is pretty good for it
but i didn't notice the stuff that had broken until i'd already done a bunch of other stuff and it was pretty rough
But yeah, it is more fragile than others
I've used this sucessfully before
i also explicitly reserialize everything after making such a change
i have a top down 2d tower defense game and when i create the level im using the following code to create the bounds for the camera
public Vector3 maxTile;
public void SetLimits()
{
Vector3 worldPoint = GameManager.Instance.mainCam.ViewportToWorldPoint(new Vector3(1, 0));
xMax = maxTile.x - worldPoint.x;
yMin = maxTile.y - worldPoint.y;
}
and then this in update to clamp it
transform.position = new Vector3(Mathf.Clamp(transform.position.x, 0, xMax),Mathf.Clamp(transform.position.y,yMin,0),-10);
this was working fine until i tried to introduce zooming in/out (changing the cameras orthographic size). i figure i need to recalculate the limits when i zoom in/out, but everything ive tried so far isnt working right, any suggestions? thank you
i don't like having "old" serialized data lying around my project
huh what do you mean by that?
I'm considering moving all of my code into assemblies, so I'm going to have to rewrite a lot of serialized references
i might just find-replace it...
[MenuItem("Pursuit/Reserialize Identifiables", priority = 10)]
public static void ReserializeIdentifiables()
{
AssetDatabase.ForceReserializeAssets(AssetDatabase.FindAssets("t:Identifiable").Select(guid => AssetDatabase.GUIDToAssetPath(guid)));
}
Unity doesn't proactively update your assets
it updates them whenever you make a change to them
It will resolve all the MovedFrom and FormerlySerializedAs stuff, instead of doing it when you touch the assets
I think it also just doesn't get rid of removed fields at all? not sure
yeah they stick around
yeah -- so I can then immediately get rid of the attributes
modify code, migrate data, done
It cuts down on version control churn, too
I hate when stuff just...changes
ok yeah i have run into that but didn't think to look for a fix, that's excellent
reserializing EVERY asset does take a while lol
i have a few of these for different categories of asset
[MenuItem("Pursuit/Reserialize Entity Prefabs", priority = 10)]
public static void ReserializeEntityPrefabs()
{
AssetDatabase.ForceReserializeAssets(AssetDatabase.FindAssets("t:Prefab", new string[] { "Assets/Entities/" }).Select(guid => AssetDatabase.GUIDToAssetPath(guid)));
}
notably
I also have some editor scripts that validate categories of assets
it's nice to be able to automatically check if you forgot something
yeah those i do have these days, at build time and/or as part of custom editors
in editor log, is the last build details at the bottom?
you probably have to do some math (e.g. if you are zoomed in 50% of the way, your bounds should be 50%...more? less? however it should be)
Yes.
If the log is way too long to deal with, just restart Unity so that it writes a new log
mine is definitely too long lol i'll do that now ty
I have a sprite sheet that has 300 sprites on it. (it's a map that is split into a grid.) If I split it and handle it via spriteatlas, can I access each sprite via an index? if not, what would be the easiest way to do this? I need to have each sprite assigned an index
can I do this via code as well
it seems i'd have to refer to my resources, but i've seen varying opinions as to whether that's a good idea or not
it just would be a pain in the bum to manually drag all 300 into a slot and potentially make a mistake esp if code can do that for me
oh, especially cause i need to do this for 3 or 4 separate sprites
it's what they're for, but no one says you can't make multiple sheets
would it be more efficient that way
i mean for the computer. or is the price about the same
i guess it doesn't matter much
i would go with whatever feels easiest to you for now
until you run into something objective you're trying to solve
probably not the right place to put this but I don't see a channel for Unity Profiler questions.
anyways I was wondering if someone could help me read this profiler data, this is my first time using the Profiler.
it looks like a script is causing me a huge lag spike when it turns 9am in my game.
at 9am my TimeOfDayController script Invokes an even that several or more other scripts listen to. that 9am unity event also activates 3 pooled car objects and run one or two methods on one of their components.
I'll include the code I'm specifically profiling -
{
carsForPurchase.Clear();
Profiler.BeginSample("For Loop Online Cars");
for (int i = 0; i < 3; i++)
{
int randomInt = UnityEngine.Random.Range(0, carIndexesAvailable.Count);
var spawnPoint = spawnLocations[i].transform;
GameObject obj = cars[carIndexesAvailable[randomInt]];
obj.transform.position = spawnPoint.position;
obj.AddComponent<CarDriveForwardArcade>();
obj.GetComponent<CarDriveForwardArcade>().arcadeVehicleController = obj.GetComponent<ArcadeVehicleController>();
obj.SetActive(true);
obj.GetComponent<CarStats>().RandomizeCarColor();
obj.GetComponentInChildren<CarStats>().RandomizeCarResellPrice();
handleActiveCars.AddCarToList(obj);
//carsForPurchase.Add(obj);
buyingCarsOnlineController.AddCarToCurrentCarsForSaleList(obj);
carIndexesAvailable.Remove(randomInt);
}
Profiler.EndSample();
ResetCarIndexList();
} ```
my movement script https://pastebin.com/B2nzCgvc
why does it stuck to the wall when i press move toward it?
Cause friction, reduce the friction of the wall
material?
A friction material can do that, yeah.
That is the normal way to create friction
okie thank
can you collapse some of those and see whats taking a majority of the 256 ms? in the current code, the only areas that could really take awhile is the method calls whos implementation which we cannot see
this has been eating at me all day. I cant figure out what i did wrong in the tutorial. I get this error:
NullReferenceException: Object reference not set to an instance of an object
DisplayInventory.AddEvent (UnityEngine.GameObject obj, UnityEngine.EventSystems.EventTriggerType type, UnityEngine.Events.UnityAction`1[T0] action) (at Assets/Player/Inventory System/Inventory/Scripts/DisplayInventory.cs:83)
at this line of code: AddEvent(obj, EventTriggerType.PointerEnter, delegate { OnEnter(obj); });
trigger is probably null
trigger.triggers.Add(eventTrigger);
I.e. there's no event trigger component on the object
three possibilities: trigger is null, triggers is null or both of them
he wrote the reference thru code, but im not seeing it trying to catch glimpses
Based on the code you need to have an event trigger component on your prefab
And it seems like you probably don't
That's not a code thing
It's a "how you set up the prefab" thing
I put the event trigger on the inventory background basically, shoudl i have put it on the button/slot itself?
I don't see an event trigger on the prefab here
Based on the code it should be on the prefab
its on the bottom right, im guessing i have it on the wrong object. I will try it on the prefab and get back toya
OMG i love all of you
come here
mwah
I'm trying to add an onclick listener to buttons that simply log out its index in the buttons array, but it's logging the length of the array instead. Here's the code:
[SerializeField] private Button[] hairSelect; //8 buttons total
private void Awake()
{
for (int i = 0; i < hairSelect.Length; i++)
{
hairSelect[i].onClick.AddListener(() => HairSelect(i));
}
}
void HairSelect(int index)
{
Debug.Log(index); //logs 8. Expected 0, 1, 2, etc
}
This would capture the i variable, so it would always be the last value it had. Assign it to a local int variable before passing it in the lambda.
@teal viper worked wonderfully, thanks!
had to redo the profiler test so values will probably vary from the first pic
Hi guys, if i put a script in a Child gameobject and want to get components in Parent gameobject in Start(). How to do that?
Why get them in Start, why not just assign them in the inspector?
Just wondering if its possible
Sure, GetComponentInParent
Alright i will test it out thanks
I'd try profiling a build to see if that happens there.
That being said the JIT could be misleading. I bet the main cause is the crazy amount of GC allocations.
Hello. I am unable to find correct way to calculate "touch" position in 3D world. Here I have added 30f randomly to get it closer. camera.transform.position.y also does not get correct value. All youtube tutotials use input.mouseposition or are 2d games 😦
screen point to ray
then raycast for 3d game
ohhhh !! is that so ! thank you so much
If II have a class A and B, Like this but this get an error public class A<T> : B<T, A<T>> I want to pass A<T> and T both to B how do I do it?
I have a question.
i am instantiating a game object with a script. that gameobject has a script component that takes in a variable called Character_Class, which is a scriptable object.
I have a scriptable object named "knight" in my Assets folder.
is there a way to create an instance of knight and add it to that new gameobject?
i Tried something like
Job job = newChar.GetComponent<Job>(); var cc = ScriptableObject.CreateInstance("Knight"); job.characterClass = (CharacterClass)cc;
It worked. I thank you with tears of joy.
why you need to do this?
I have a class need to inherit singleton, in addition, I need this class to inherit another class
I cant inherit 2 class the same time
if I use parent class to inheired singleton.It will create parent class instance.That's not what I want
Maybe there're some solution or some alternative?
That doesn't make sense. Generics don't change how inheritance works in C#, and you can't inherit from 2 classes.
And I'm not sure if this kind of recursive generics are even allowed. I wouldn't mess with them too much.
abstract class Singleton<T> where T:class{}
abstract class Middle_0<T>:Singleton<T> where T:class{}
class Leaf:Middle_0<some class>{}
```child class having all properties parent class has (an "instance" of parent class is created but stored inlinely), no idea what do you mean by "dont want parent class instance" but you want child class inherits parent, instance of child class can be treated as instance of parent class
if you mean by stopping others create an instance of that parent class, use abstract
...
GoldenLeaf.Instance.func().....```
This will create Leaf instance instead golden leaf
I want to create goldenleaf instance
GoldenLeaf is a class. "Create goldenleaf" doesn't make sense in this context.
Unless you mean an instance of GoldenLeaf
Oh, misreading the message again lol
This wouldn't create anything. It accesses the Instance and calls it's func
where T : MonoBehaviour
{
private static bool applicationIsQuitting = false;
private static T _instance;
private static object _lockObj = new object();
public static T Instance
{
get
{
if (applicationIsQuitting) { return _instance; }
if (_instance != null)
{
return _instance;
}
if (_instance == null)
{
_instance = FindObjectOfType<T>();
}
if (_instance == null)
{
lock (_lockObj)
{
GameObject go = new GameObject("[MonoSingleton]" + typeof(T).Name);
_instance = go.AddComponent<T>();
DontDestroyOnLoad(go);
}
}
else
{
DontDestroyOnLoad(_instance.gameObject);
}
return _instance;
}
}```
Singleton class will create gameobject then attach component to it
Okay, yeah, that would create and return a component of type T, so what's the problem?
please replace the leaf to your actual implementation....
it is just a place holder.... (the leaf node in your inheritance tree....)
public class MyMonoSingleton<T> : MonoBehaviour
where T : MonoBehaviour
```no need to constraint T as monobehaviour
everything inherits from this is monobehaviour
I was intened to split the code into 2 class. Dont want them crowd in a single class tho
Abstract may be impossible
You could use a partial class, but I feel like there's a bigger design problem due to you overcomplicating
If that case,how to create a gameobject and add component...
if i have a class EnemyManager
which inherits from your singleton
class EnemyManager:MyMonoSingleton<EnemyManager>
```is it monobehaviour?
you didnt actually require T has any special properties (in this case you will need interface), you just need its type
I actually have the "Network" class and "NetWorkClient" class. One is handle the socket and packet. The other handle state , time, replication and so on
Okay, but how is that related to the question?
I have NetWorkClient inherited from NetWork. And NetWorkClient need to be create instance and show in the scene
I still don't see how it's related to the question? I wouldn't have these classes as singletons in the first place. And even if I do, I'd either implement it as Tina suggested or avoid generics entirely and just implement the singleong logic within it.
I havent try interface yet.But I think my design has some limited. If I do A inheried from B, B inheried from Isomething, this may come back to class inheritance problem
mb, nvm
it should be abstract function not interface
public abstract class Root<T>{
public abstract void MethodA();
}
public abstract class TreeNode:Root<int>{
public override void MethodA(){
the implementation;
}
}
```if you need child class to have some methods
My 2 Class are sperate. there's no override
Mornin' all, having the weirdest issue and can't see what I'm doing wrong. IDE (VS) is all configured properly, but for some reason it's not 'picking up' Random.Range. I've used it so so many times before, but it's just stopped recognising 'Range' 😕
I found a way.I can use type of the get the type of A<B> (B : A), and B is exactly I want
do you using System; or using Unity.Mathematics;?
Weird. Genuinely never had that issue before, but using UnityEngine.Random fixed it.
Pretty common, make sure you have the error bar open though.
Pretty sure that tells you exactly what the problem is
For this error
Error list is the name
i haven't profiled in a build yet, but i did test out a build to see if it still did the lag thing at the 9am event and sure enough the lag spike happened in the build.
and also why do you think there's so much GC? and how could i possibly fix that
You'd need to share the code for me to be able to answer that question properly, but basically, you're allocating a lot of memory on the heap is the problem.
I shared the code earlier but I can post it again.
this is the "For Loop Online Cars" profile test I made for the following code -
{
carsForPurchase.Clear();
Profiler.BeginSample("For Loop Online Cars");
for (int i = 0; i < 3; i++)
{
int randomInt = UnityEngine.Random.Range(0, carIndexesAvailable.Count);
var spawnPoint = spawnLocations[i].transform;
GameObject obj = cars[carIndexesAvailable[randomInt]];
obj.transform.position = spawnPoint.position;
obj.AddComponent<CarDriveForwardArcade>();
obj.GetComponent<CarDriveForwardArcade>().arcadeVehicleController = obj.GetComponent<ArcadeVehicleController>();
obj.SetActive(true);
obj.GetComponent<CarStats>().RandomizeCarColor();
obj.GetComponentInChildren<CarStats>().RandomizeCarResellPrice();
handleActiveCars.AddCarToList(obj);
//carsForPurchase.Add(obj);
buyingCarsOnlineController.AddCarToCurrentCarsForSaleList(obj);
carIndexesAvailable.Remove(randomInt);
}
Profiler.EndSample();
ResetCarIndexList();
} ```
@teal viper ^
I'd assume that AddComponent is the culprit here. Is CarDriveForwardArcade a heavy class? Does it allocate some stuff in the Awake/Start/OnEnabled as well?
Hi guys, I am working on a little game, and I have made some animations for my character, however they are very delayed from when I press my input buttons, I can provide code and a video if needed.
My animation tree looks like the image, and I have removed exit time as I thought that might be the cause, but still nothing
CarDriveForwardArcade is a pretty simple class, it has a car gameobjet go forward in one direction for a few seconds.
could possibly be the RandomizeCarColor() method in the CarStats script
Can you share both?
My code is the following: https://sourceb.in/xfJi5jjsd5
Can you record a video of the issue with the animator visible as well, so that we see the transition in real time?
I understand this method does more than what it should and I plan on refactoring it soon, but for now i would like to explain that i'm using the ES3 Easy Save asset. and the reason i'm temporarily saving to a different file and reloading it is because cars seem to drift better after they have been saved and reloaded. It's hard to explain but the car controller I'm using, pretty sure it's Arcade Vehicle Physics, will save a bit different and a car instantiated or set active in the scene drives a bit differently than a car that has been loaded from ES3. I couldn't find what or why it would change the car handling but it would so to keep the handling consistent on the vehicle i will save and load first and get rid of the temp save data in the temp file. anyways, here's my code -
public void RandomizeCarColor()
{
float randomNumber1 = Random.Range(10, 90);
float randomNumber2 = Random.Range(10, 90);
float randomNumber3 = Random.Range(10, 90);
randomNumber1 = randomNumber1 / 100;
randomNumber2 = randomNumber2 / 100;
randomNumber3 = randomNumber3 / 100;
spawnColor = new Color(randomNumber1, randomNumber2, randomNumber3, 1.0f);
oldCarMaterial.SetColor("_Color", spawnColor);
metallicValue = 0.35f;
oldCarMaterial.SetFloat("_Metallic", metallicValue);
ChangeMaterialsOfCar();
carID = this.gameObject.GetInstanceID();
ES3.Save(carID.ToString(), this.gameObject, "tempCarData.es3");
this.gameObject.SetActive(false);
GameObject obj = ES3.Load(carID.ToString(), "tempCarData.es3") as GameObject;
obj.SetActive(true);
if (ES3.FileExists("tempCarData.es3"))
{
foreach (string key in ES3.GetKeys("tempCarData.es3"))
{
if (key.Equals(carID.ToString()))
{
ES3.DeleteKey(carID.ToString(), "tempCarData.es3");
}
}
}
} ```
For future, use the !code sharing guidelines:
📃 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.
It looks like it can't exit an animation early
is there something I need to turn off or on?
ok thanks, sorry about that
With the jumping animation, if I only jump low, it doesn't have time to finish the jumping animation before falling and instead just plays the jump animation on the way down as well
I've no clue what ES3 and what save and load methods do, but if they actually save and load from disk that would explain the lag spike. Disk operations are super expensive and isn't something you should be doing at runtime on the main thread. At least not with heavy objects, which your cars seem to be.
Can't say for sure without seeing your transitions.
Yeah, fixed duration would make the transition last a fixed duration
okay the jumping is much better now
but the running is still weird
i think it might be because i check the velocity of the rigid body, I should probably check for user input
is GetAxisRaw just returning 0 or 1?
nvm -1 to 1
Yes.
Is there a way to stop animations from fully finishing before transitioning?
Almost everything works now, but if I stop running, it finishes the running anim fully before switching to idle, which causes the player to keep running in place for half a second, looks kinda odd
I can do another vid
Share the transition settings to idle
Mmmm... I think it's the "Has Exit Time" checkbox
But I can't turn that off as long as it doesn't have any conditions
Yeah, you'll need some kind of condition. Otherwise, it would transition to it all the time.
Should I just put the conditions that nothing else is on?
Yes
Ah, well, then you'll need to think about your setup overall.
In the first place triggers don't make sense for stuff like running, as it's a continuous state
hm, i tried just using my booleans and if they were false, but that doesn't work at all lol, then it just spams idle
I know, I don't use it for running
I have it for Jump, Attack, TakeHit and Death only
Then you'd probably need transitions from each state to idle
For example, Attack shouldn't transition to idle immediately, but Run should
You can't use one transition from every state as they all have different requirements.
Oh okay
Can I setup different conditions with the "Any State", or do I have to do transitions between them?
You can't since you don't know what state it would be coming from. You'd need to make explicit transition from other states to idle.
Okay, I'll do that, thanks 😄
yeah that was mainly the issue, saving and loading all three cars at the same time
now i only save and reload the car gameobject if it was purchased and is now drivable by the player and that seems to work pretty good for me so far
normalised time is correct. I think the issue is in curveDisplacement or the way the math works. However, i am not very good at 3d space math.
hi, is there a way to print two elements without using for loop?
Debug.Log($"{sums[i]} and {sums[j]}");
thanks!
player prefs no
why not?
persistency problems compared to just using json
alright thanks
also limited serialization, even though json utility isn't that much better
grab the newtonsoft package
There are two different things to consider.
One: How do you turn the inventory into data?
Two: How do you store that data?
PlayerPrefs and a JSON file are how you store serialized data
But you still need a way to actually do the serialization
JsonUtility can perform serialization, as can Json.NET (and the latter can handle much more complex data)
