#π»βcode-beginner
1 messages Β· Page 23 of 1
This is what it looks like, I want E to be the action key, anything wrong here?
you set it as Type: "joystick axis"
it should be a keyboard key
or whatever that option is called
{
while (_camera.fieldOfView != targetFov)
{
_camera.fieldOfView = Mathf.Lerp(_camera.fieldOfView, targetFov, duration);
yield return new WaitForSeconds(Time.deltaTime);
}
}
For some reason this coroutine is zooming in the field of view faster than it should I put it at 1 second but it goes to the target FOV within .1s
not sure what this is even supposed to do
yield return new WaitForSeconds(Time.deltaTime);
Hey. for some reason my player character tends to walk towards the left randomly without me giving it any input. i already looked at the debug.log and it seems that sometimes it gets an random input which is like -0.00068 and so on. Here is the method which handles the running
void Run()
{
Vector2 playerVelocity = new Vector2(moveInput.x * runSpeed, rigid.velocity.y);
rigid.velocity = playerVelocity;
bool playerIsMoving = Mathf.Abs(rigid.velocity.x) > Mathf.Epsilon;
if(playerIsMoving)
{
myAnimator.SetBool("IsRunning", true);
}
else
{
myAnimator.SetBool("IsRunning", false);
}
}
because you cannot declare a variable in the middle of that API call
and what shall i do
transform.parent?
I want it to instantiate under a certain object
i tried yield return null but its supposed to be for one frame
Either x isn't zero or other forces are causing you to have velocity in the x axis - assuming you're referring to velocity with the value.
i havent took a look at the api yet, you have to check it
Maybe explain what you're trying to do
Its a coroutine to set the field of view of the camera kind of like a zoom in zoom out function
you need to lerp the correct way
How so? (that much was given already)
Bruh. Thanks for the Answer. My Controller was plugged in and has Stick drift. thats why i had the problem
Transform: the type.
transform: the game object's Transform on which this script is attached to
C# is case sensitive, these two names mean something different entirely.
i feel stupid right now
example of good lerp
IEnumerator LerpFunction(float endValue, float duration)
{
float time = 0;
float startValue = valueToChange;
while (time < duration)
{
valueToChange = Mathf.Lerp(startValue, endValue, time / duration);
time += Time.deltaTime;
yield return null;
}
valueToChange = endValue;```
Using the lerp function, it tries to set the current FOV to the target one but at the speed of the duration float. It's going faster than it should right now but its not iinstant
thanks ill try with this one
I tried this
didnt get what i wanted
Well at least it compiles now
you still haven't explained what you do want
Use the appropriate lerp with a fixed start and end value with an accumulative third value.
I want to instantiate under the object i click in the hierarchy
idk man
making a board gaem is way difficult that platformer
but which object is this?
which meaning ?
You want clickedTile.transform most likely (the tile you hit). Not the parent of the tile you hit
hmmm
its not doing it
it still shows up hierarchy under scene not where i want it
Then it's the second Instantiate that runs, when it's not "the tiger's turn"
Hello,
If I raycast the Terrain with the boxcast, will it return only the first point to touch terrain, or every point?
I am trying to implement a tool that affects the terrain in a certain area
First point. A box cast is merely just a thicker raycast
I see, do you have any suggestion to my problem? I tried defining a starting and ending corner and simply looping from one to the other, but it seems bad
specially since raycast coords and texture coords operate on separate spaces
Hello, I am instantiating a ground (basically a cube) with some enemies on it. After I kill the enemies in the first ground, rest of the instantiated grounds comes with allready dead enemies. I thought every prefab was suppose to be unique and not get effected by the previous alterations. Any idea what I am doing wrong ?
probably re-instantaiting the ground gameobject rather than the ground prefab
I drag from the prefab folder not the game object in the scene
I meant in your code
a little frustrating π
Instantiate(groundCube, RBspawnPoint.position, RBspawnPoint.rotation);
this is the code I use
just that?
' public void OnTriggerEnter(Collider other)
{
if (other.tag=="Player")
{
Vector3 direction = Vector3.right;
Ray theRay = new Ray(rayStart.position, rayStart.TransformDirection(direction * range));
Debug.DrawRay(rayStart.position, rayStart.TransformDirection(direction * range));
if (Physics.Raycast(theRay, out RaycastHit hit, range))
{
if (hit.collider.tag == "Ground")
{
//Debug.Log("cant spawn");
bx.enabled = false;
}
}
else
{
Instantiate(groundCube, RBspawnPoint.position, RBspawnPoint.rotation);
//bx.enabled = false;
}
} '
so how do you parent your enemies to the ground?
!code
π Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
ok so you are only working with the prefab, never with the GameObject created from the groundCube prefab
thats right
no, thats wrong, that is why your enemies are dead when you instantiate again because you are instantiating the same object which you just used
@languid spire thanks for the help, at least now i know I am doing it wrong. I will try to find a solution
Solution is easy
GameObject groundGO = Instantiate(groundCube, RBspawnPoint.position, RBspawnPoint.rotation);
then use groundGO in the rest of your code instead of groundCube
thanks Steve I will implement it right now
Just tested, it returns only one collision per collider. Say I am checking the ground and want the coordinates bellow something, the box will only return one coordinate of Terrain
how can i make this shorter?
https://hastebin.skyra.pw/unuvudibah.wren
and make it better
or does it look fine?
That's 65 lines. What're we supposed to look at?
there is a lot of repetition
whole method
i feel like its too long
for what its actually doing
yeah
You could probably refactor it for readability else opt to not create a new instance of the list or create it with a set capacity to avoid garbage collection etc
its first checking if there is an object open with an inventory
so an object that has slots
nvm yeah
and if it does you first add those slots to the list
instead of GUIText.pixelOffset what can i do?
for an fps should the bullets be invisible and have them shoot from the camera?
or visible and make the crosshair accurate to where the gun is pointed
depends what you want
which is better
there is no better
for a simple game from camera is probably better
if you want physics bullets
then go with them coming out of the gun
and using physics
if not its prob better to use a raycast from the camera
yeah
In this image, assuming this is all on 3D space. The red is my vehicle, I have access to the BLUE dots coordinates. How can I find the Terrain coordinates of the GREEN cells?
I want to change the texture of those cells in specific
@languid spire I could not get it to work so I gave up on prefabs spawning prefabs (they just clone their curent state) , intead I have created a spawn manager that with a puplic function and the prefabs just feeds the next spawn point to the script and the manager spawns the prefabs. This works like a charm. Thanks again for the help
void SaveData()
{
PlayerPrefs.SetInt("higscore", highscore);
int button;
if (buttonEnable)
button = 1;
else
button = 0;
PlayerPrefs.SetInt("buttons", button);
Debug.Log("Data Saved: "+button +", "+ highscore);
}
void LoadData()
{
highscore = PlayerPrefs.GetInt("highscore");
buttonEnable = (PlayerPrefs.GetInt("buttons") == 1);
I want to save int highscore and int buttons
hmm and ur certain you called these two?
yeah
this isn't the entire script..
Anyway.
Try adding PlayerPrefs.Save after SetInt
should I post the entire script
Man, this concept of a prefab referencing in scene components just isn't computing
idk how
references should be one of the first things you should learn and learn it well. Its the core concept of working with Objects
also what you should and shouldn't reference between what
sry
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
the entire code
:)
my firefox search being weird rn
wait yea
OnLevelWasLoaded() isn't called anywhere
therefore LoadData is never actually called
but OnLevelWasLoaded was shown in Blue for me so I thought its a build in like Update and Start
2021.3.13
sry
well
use the SceneManager instead
is there an alternative
to subscribe to level changed
so like which method
also can do
Scene scene = SceneManager.GetActiveScene();
if (scene.buildIndex == insertSceneBuildIndexHere) {
//Do something
}
if (scene.name == insertSceneNameHere) {
//Do something
}```
started here and I'm scared to move
nah nvm you edited that message , you said originally 3.13
i thought you were on unity 3.13 lol
oh ok
your function is before unity 5 was a thing
thats like more than like 5-10 years now iirc
ooooh
u can duplicate ur entire project folder and rename it.. open the copy through the newest version or (newer) version of unity..
if it doesn't work on ur project u still have the original.. but yea ur missing out on so much new stuff π
oh nahh they're on 2021.3.13
they're fine
their original msg said 3.13 lol and was presented with a function from unity 3.
lol
I put the two together wrongly haha but still they used deprecated function I didn't know existed on MB
ignore me.. i thought u were using a version older than 5
I think I just accidentally deleted my Project...
jeah
its in ur recycling bin
good time to learn Version Control before going futher
who Invented this...
someone at Unity really thought "lets change duplicate into delete XD"
yea i think its a bad hotkey imop
once u get used to it.. its liable to screw u over in other programs
as D is delete sometimes
used this I think it works now..
Shift + Del permanently deletes in windows
thast a real bad key.. thers no recoverying that
everything is technically recoverable
Im creating this for android but I dont have one for my own so I can only test it in the editor... where it doesnt work
it should work
u can still simulate android devices thru the editor
I do
sadly i have and true they're trash but somehow found one to recover all my Sony DSLR videos I shot for someone
saved me $$$ from being lost in stupid format mistake π
u can buy a pre-paid phone for cheap
it still doesnt work
dont have that money
Debug.Log the function of load
make sure its running at all
oof, ^
"doesn't work" isn't helpful
sorry
Log
doesnt matter what u write for this one
@ivory pollen sorry to ping you, but i've just realised that the error happens almost every time when im compiling InventoryManager.cs
VS stopped working π
restart, and try again π
π
and it also logs data savedd
make sure you have ur scene plugged into the build index of the project
it is
ok good, just thinking of the common mistakes
show new script
1 sec
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
what doesn't work?
you say "Loaded" is called.. which makes sense.
but thers nothing in that function that actually loads a new scene
in a 2d project how to do you make things follow alongside the wall collider? like in this clip from an old NES game, the fireball follows the wall after hitting it. and also those little ball enemies follow along the wall as well
Played by: Reinc
When the world was still in a state of chaos, evil spirits roamed the world freely and rioted. The magic document "Key of Solomon" was the product of great King Solomon's magical research. It described how the evil spirits were confined to the underground constellation Miya. Centuries later, one man so...
no the data is loaded
When I call Die() the player reloads the scene and should load the highscore data but he doesnt load the highscore
its set to 0
https://forum.unity.com/threads/make-character-follow-along-walls-ceiling.1220904/
peep this thread.. might be something there for you
so ur saying that Debug.Log("Loaded");
is called on which scene exactly
and when
make sure you have data also
void LoadData()
{
Debug.Log("Loaded");
if(PlayerPrefs.HasKey("highscore")){
Debug.Log("Has Highscore saved");
}```
eg
first when I load the scene with the player in it. then when I die once
so each scene reload or no?
every time the scene reloads
ok
and you checked the if statement I sent you
PlayerPrefs.HasKey("highscore")
see if the value is there so you know thats not the problem
?we're talking about the log here, forget the 0 for a second
how come when i use cinemachine 2d all my gameobject sprites disappear
Alright thx, i deleted it!
doubt its related to cinemachine
it is
is the new camera somewhere else?
b4 i added it i can see the gameobjuects nd stuff
not a code question. but you need to offset your camera so that it is not at the same Z position as the rest of your objects. it's typical to put the camera at -10
then the new "Added" camera is in the wrong position than ur main cam
so it doesnt show the "Has Data" Log
ok so your data isn't there
yeah
Debug.Log("Loaded");
if (PlayerPrefs.HasKey("hightscore") && PlayerPrefs.HasKey("buttons"))
{
Debug.Log("Has Data");
highscore = PlayerPrefs.GetInt("highscore");
buttonEnable = (PlayerPrefs.GetInt("buttons") == 1);
}
strings?
hightscore
...
Misspelled in the if statement
:(
Misspelled everywhere :/
Use a const string variable !
const string Highscore = "highscore"; and then the compiler backs you up
thats why we use a variables for the same thing
idk how I didn't see that earlier lol
Type it wrong, and you get an error in the code directly. Change its value, and it's reflected everywhere. Absolute win to use const in this case
whats correct chat
I was sitting there looking for mistakes...
#πβfind-a-channel to find a relevant channel for your question
ty
I want to change my script so I can call Save Data and Load Data without having a Player Movement script appended
is that solved with static classes?
not necessarily. if your Save and Load methods are on the PlayerMovment script then you need to move them to some other class. depending on your needs it could be an instance in the scene, a scriptable object, a static class, there are many ways to go about it
is it possible without a gameobject carrying the script
like I want to call it in every scene
"instance in the scene" would be the only option i suggested that requires it to be attached to a gameobject
oh
of course that still doesn't preclude it from being accessible in every scene
So like when I use a static class how would I do this?
why not go find a tutorial to follow?
that's really only true if you are only watching terrible tutorials that don't explain the process and just basically dump code on you instead
most of them are like this
Hi! I am very new to unity and started like 5 days ago. Im workin on a Gorilla Tag fangame using XR. Lately ive been getting this error called β A native collection has not been disposed, resulting in a memory leak. β can someone please help me? Im scared i might lose my project.
You're not going to lose your project
You should be using version control to prevent any unexpected data loss though
I.E. Git
That error is quite generic and unless you're dealing with the Job system or DOTS it's not related to your code
Ok tysm and im gonna see if it helps
I have this problem. Basically I am trying to set the position of a object that I instantiated but it is not going where I want it to I tried local and world position but both seem to have the wrong x value and y value here is the code snipit that makes and sets the position ``` for (int i = 0; i < PlayerInventory.i.Soc.Count; i++)
{
currentButton = Instantiate(ButtonTemp, parent.transform);
if(xpos < 556.2f)
{
xpos += 188.2f;
}
else if(xpos >= 556.2f)
{
xpos = -571;
ypos -= 170;
}
currentButton.transform.position = new Vector3(xpos, ypos);
}```
What's up with these magic numbers
Also is this a UI element?
You should be using the recttransform layout system to position your UI elements, not setting the position in code directly
Forgot about recttransform thank you
i have got this error Assets\scrips\PlayerMotor.cs(5,14): error CS0101: The namespace '<global namespace>' already contains a definition for 'PlayerMotor'
can someone help
you have a duplicate class/script
i do not i cheked
bet
The error says you do
look
If you show one folder, I will tell you it could be in a different folder
it could even be in a completely unrelated script
"it could be in a different folder" ah, that is search
Or a different script, as Steve said
Look through your scripts for PlayerMotor
Search using the IDE
<@&502884371011731486>
???
They... can see deleted comments btw
ok well bye
Do you know what an IDE is?
Like visual studio
i gess
idk what you saying
the thing you type code in....
yes
... use its search function....
No
You gotta just learn to google things. If you don't know what an IDE is, google it.
If you don't know how to search in it, google it.
You will find all your need. I pointed you in the right direction, and Steve told you the answer/reason for the error
You have another PlayerMotor. Find it
mate you're too young to even be on discord. how you gonna ask strangers to call you
bc you will get my ip from a call
i play val
and fn and rl and on mc severs
congrats. did you know that you are breaking the TOS for most of those services? but that's off topic from here. you should probably leave this server until you are old enough to even use discord
i remember having to stop using the Gruntz! fan-forums because I was 12
or maybe 11, i forget
is there a more clever way to make a bidirectional map than to just have two dictionaries?
i guess i can just make a little class
hey guys I dont know were is the best way to post for this, but my update start or any trigger enter are in gray, the compiler is ignoring them and I have this error when I hove with the mouse "Private member 'NewBehaviourScript.Start' is unusedIDE0051"
any ideas?
Does the class derive from MonoBehaviour?
i.e. does its first line look like public class NewBehaviourScript : MonoBehaviour
does the code run?
no
Show your code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
// Start is called before the first frame update
private void Start()
{
print("Hello World");
}
// Update is called once per frame
void Update()
{
}
}
looks fine. If the code isn't running you haven't attached it to an active GameObject in the scene.
if the IDE isn't recognizing those as unity messages, it's not configured properly for use with Unity
its attached man, I work with unity for more than 2 years now, this is not the problem
we are attempting to help you.
humm how so?
Show it and show your console
sorry dont want to sound condecending, just want to help to dessmiss newbi problems
console clear
show screenshots
of your inspector, of the console
maybe just the whole editor window in play mode with this script attached to an object in the scene
HAHHAa
lool
yeah its there
the hello world
omfg
I feel ashamed
thanks
I was used to the warning messages to be there already
since a very long time
it literally just calls Debug.Log, yes
bruh
it's to make python people more comfy
didnt know
it only works for the single parameter overload of Debug.Log though
oh
alright
easier way to write this?```cs
foreach(var cell in hotbarCells)
{
cells.Add(cell);
}
foreach(var cell in inventoryCells)
{
cells.Add(cell);
}```
cells.AddRange(hotbarCells);
cells.AddRange(inventoryCells);```
alright thanks
or
List<InventoryCells> cells = hotbarCells.Concat(inventoryCells).ToList();```
(with `using System.Linq;`)
Does anyone have a script for a 2d.mobile game that lets you move side to side
That is pretty basic. Just any "2d player movement" tutorial should do it
What part specifically are you struggling with
not posting the same question in four different channels, it appears
Oh shi-
And one of the channels is #archived-code-advanced !? Lmfao
What would be a good way to keep track of a bunch of stats? I'm talking about things like.. "Used a weapon X amount of times" or "Died to X this amount of times" or even things like "Saw NPC X amount of times". I guess a generic way to track things? Obviously, I don't want to use PlayPrefs, so I'm trying to think of a generic solution where in editor, I can define the key etc? Iunno. Thoughts?
Sure, but mroe so an overarching system.
I think I stumbled on the Termanology which is called Blackboard.
No clue with termanology of the stuff, but what you want is basically just a struct.
if you have like say multiple players, then perhaps some singleton via gamemanager, but even then just stick it on the players and access it
You need to decide how you're identifying each stat
Maybe enums, maybe just a bunch of constant string keys
Yeah, thats kinda what I'm trying to figure out. Whats the best way to track the things I want to track, and how to go about tracking them.
I guess I'm looking mostly for design priciples. I assume this has been done in the past.
I was dealing with the same problem a few months ago
Didn't really "solve" it, per se
I'd just cache it all honestly
I wound up storing each kind of stat separately (floats and ints)
and using enums to identify them
Enums are annoying because they'll go haywire if you rearrange them. Assigning explicit values fixes this
I guess if there is a lot of stuff you want to keep track, then perhaps some string/value dictionaries
if the purpose is to just display it to the user
As for storing the data: just use Json.NET to serialize a dictionary, if you go with a dict
There will be events fired from said values as well, pending whats going on.
oh, this isn't strictly stat-tracking
Yeah thats what I figured I'd do.
you want to have reactions to these
Correct. Mixture of both really?
In that case I'd say you should make a class that holds a delegate for every kind of stat
so that you can subscribe and unsubscribe
If you want to do stats per-item (e.g. "kills with X" and "times Y used"), you might want something smarter than just a big blob of string keys
The idea being is like. If a player steps on a spike trap, say, every 10 times, then they should say something about it. Or, say on the 10th attempt of a boss, a cutscene happens. But then also, I want thinks like generic stats like you've died to this enemy X amount of times" etc.
I mean, you could totally do $"stat-{weaponIdentifier}-{statKind}"
problem is unique stuff and how much you want to display that
but i might lean towards something more polymorphic
like how are you deciding between two different instances of an iron sword you killed with. In this case, either merge the kills together, or add the higher of the two.
so a Stat could be a SimpleStat, that's just a string key
or an ItemStat that holds a reference to an item kind along with which item stat it represents
the idea being that you could construct an ItemStat as needed to look up "number of kills with X item"
You'd just need to override GetHashCode so that the same item and the same stat always gives the same code
then it'd work nicely in a dictionary
Hmm.
conceptually, this isn't much different from just doing this
but it would survive a weapon rename
well, you would ideally avoid changing the identifier if you were using string keys
you'd just change the display name if needed
Actually, I'd keep track of those types of stats on the weapons themselves, but depends on the usecase here and not just like an achievement style kind of display
I'm not sure which would be smarter. I might try doing this.
Well, I already have SO's tied to all of my enemies, weapons, and a few other things.
I could easily tie a "Key" to them to use for keeping track of stuff.
Then from there do sort of what you are saying, so, using playprefs as an example (Dict Json instead)
PlayerPrefs.SetInt(weaponID-TimesEquiped,value)
or
PlayerPrefs.SetInt(enemyID-DiedTo)
etc.
If you need a unique identifier for each SO asset, you could just copy the asset GUID into a field on the scriptable object
Did you want to use playerprefs? I thought you didn't want to.
It's a little funky (you have to make your own serializable GUID)
I just said as an example to explain what I was thinking about doing. It would just be a generic <String,Object> Dictionary/Map.
Ideally, just use non-unique cases, this way you can just use the SO IDs when possible.
I'd probably just, on the SO, make a field called "UniqueIdentifier" for me to plugin. So when I read the stats file, it would be in plain text and easy to read.
And even then I can have a enum system setup for the events I want to listen for, which, probably is a decent idea.
// Get the asset path of the Scriptable Object
string assetPath = AssetDatabase.GetAssetPath(this);
// Get the GUID of the asset and set it
storable_ID = AssetDatabase.AssetPathToGUID(assetPath);
For the asset ID
So building out the StringDict would be like.
weaponID + Stats.Equiped
or even enemyID + Stats.Killed
(I think thats what I'll do, keep it simple/small).
I can still hook up some sort of events to it as well.
how do you get your code inside that little box with those color codes
```csharp
//CodeHere
```
ohh, thank you
best thing to do is to reply to the email you got sent with that information, so that it gets attached to the bug report itself
How can i get the sword sprite to always point in the direction the player is facing. aka the mouse? I spawn it in as a prefab so dont have it equipped to the player but to a weapon holdster. hope that makes sense
in this short clip, https://streamable.com/na3c7p , you can see in the first character jump he doesnt make it all that far, but if i spam attack while hes in the air he can travel a lot farther before touching the ground. i tried to make it so the gravity and velocity are 0 while the animation is playing with the intention of having the character temporarily freeze in place, i dont really want them to travel more. what do i need to do to fix the code?
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
// Get input in Update
moveHorizontal = Input.GetAxis("Horizontal");
if(moveHorizontal < 0)
{
movingLeft = true;
}
else if(moveHorizontal > 0)
{
movingLeft = false;
}
SetAnimation();
// Jumping
if (isGrounded() && Input.GetKeyDown(KeyCode.Space))
{
jump = new Vector2(rb.velocity.x, jumpForce);
}
if (Input.GetKeyDown(KeyCode.Mouse0))
{
Attack();
}
}
void FixedUpdate()
{
if (attackLeftRenderer.enabled || attackRightRenderer.enabled)
{
//rb.velocity = new Vector2(0, rb.velocity.y);
rb.velocity = Vector2.zero;
rb.gravityScale = 0f;
return;
}
else
{
rb.gravityScale = 2.5f;
}
Vector2 movement = new Vector2(moveHorizontal * moveSpeed, rb.velocity.y);
rb.velocity = movement;
if (jump != Vector2.zero)
{
rb.velocity = jump;
jump = Vector2.zero;
}
}
you're resetting the effect of gravity back to 0 every single time you attack. gravity is an acceleration so it continuously increases the magnitude of the velocity.y. each time you attack you set it to 0 so it has to start over once the attack has been completed therefore allowing you to stay in the air longer
Yeah but I tried and it didn't work
Can't really help with no information.. π€·ββοΈ
What does "didn't work" mean? What did you try?
I mean, it's just moving back and forth. It's the first thing you would learn in any unity tutorial.
https://learn.unity.com/pathways is always what I recommend. Choose a path and go through all of it.
So it's equipped as a child to the player? You'll have to get the mouse coordinates and then use that with your sword position to get a direction. Since the sword is local to the player, you'll have to take that into consideration too.
I would of thought it would be similar to my shotgun bullet spray as i rotate the sprite for that depending on my mouse - the projectile
hm i set gravity to 0 because i could see the sprite sinking during the attack animation and didnt like the look of that. if i dont touch the gravity then yeah it lands where i expect it to. but is there a way i can get what i want and have it freeze mid air and still not travel farther?
Oh, if you got a working methods then try it out. There's possibly otherwise to do this, but I'm just giving the general idea.
store the Y velocity at the time you begin your attack. apply it after the attack has finished
ill try that, thank you!
of course that will allow you to continue rising if you attack before the peak of the jump so if you don't want that to happen you'll need to check for that as well
When I put it on the object I wasn't able to move the object
Vector2 direction = mouse.transform.position - gun.transform.position;
//world space direction to local space direction.
Vector2 localDirection = transform.InverseTransformDirection(direction);
Vector2 localDirectionNormalized = localLookDirection.normalized;
transform.right = localDirectionNormalized ; //or transform.up
Ah, is there a 2D lookAt?
no. you just assign either transform.right or transform.up to the direction
oh yeah I guess that makes sense
That is equally unhelpful. You put what on what object? Show code, show screenshot of the inspector for the object, share the tutorial you used. Give details lol
i still can't get it to work
i don't know what you tried or really most of the context of your issue
my sword is always facing up. it doesnt rotate with the player.
I'm spawning a prefab which is where I'm getting confused. I have it so it spawns on my player but cannot get it to swing in the direction the player is facing
if it has been more than 4 hours you should see a doctor /s
show how you have it all set up and any relevant code you have right now
hehe
I'm aware the move towards is wrong. I had it really messy but this is kinda what i was working with
using my shotgun bullets as referency - the shooting
well for starters, you only ever change its rotation one time
so it will be rotated in whatever rotation the player has when this originally spawns and then never rotated again. unless something in the hierarchy is affecting the rotation, but since you haven't bothered showing how your hierarchy is setup i can only assume nothing is rotating it
and which object in that screenshot has the component you shared the code from?
The code is on my sword prefab which spawns whenever I press my mouse button. i'll show it now
it spawns on the FirePoint transform
i see that you give it the FirePoint's position. but is it actually a child of that object?
yes. The "Dir" is a bit infront of my player.
please show the entire hierarchy during runtime when you expect this object to face whatever position it is not currently facing. these screenshots where the actually important context is either not provided due to not being in play mode or is cut out because you decided to crop the hell out of it is not helping
you'll also need to confirm that you have frozen the rotation on the rigidbody so that physics is not affecting the rotation. and check any animations you have to ensure those are not also affecting the rotation
void DestroyBlock(Vector2 pos)
{
pos.x = Mathf.Round(pos.x) + 1;
pos.y = Mathf.Round(pos.y);
Debug.Log(pos);
if (Physics2D.OverlapBox(pos, Vector2.one / 2f, 0f, destructibleMask))
{
Vector3Int cell = destructibleTiles.WorldToCell(pos);
TileBase tile = destructibleTiles.GetTile(cell);
if (tile != null)
{
destructibleTiles.SetTile(cell, null);
}
}
}
i have a 2d tilemap and had to put a tilemap collider2d and composite collider 2d on it to fix an issue where the player collider was getting stuck on it. but with the composite collider the code above doesnt work to destroy individual blocks, is there something i can change so i can still destroy an individual block but use the composite to avoid the stuck issue?
i have a plane that shoots and it used to work correctly but i decieded to delete the prefab and recreate it and it shoots until the bullet object in the hierarchy gets destroyed by going to far away and if i delete the gameobject it doesnt shoot
anybody know why this might happen
it sounds like you're cloning the bullet object that is in your scene instead of a prefab
well the instantiate is on the script that is on the bullet prefab so idk how i would not be cloning that
dang it ur right i dragged it from the hierarchy to a diff script instead of the prefab
Whats the proper way to return T?
public T GetValue<T>(string key) {
if (typeof(T) == typeof(int)) {
Stat stat = blackBoard.FirstOrDefault(stat => stat.key == key);
return (T)stat.intVal;
}
return default(T);
}
i think you should return as int
Is there a Mathf function that allows me to lerp a float starting in a way that starts off really high then end slowly or would I need to use an animation curve?
lerp is linear interpolation. you need to create the easing yourself using an animation curve (easiest method) . . .
alright thank you
honestly the best to do it. easy to customize and change the anim curve . . .
sorry about the topic again and sorry for responding late, does that code cause them to be deleted in order from first to last? because I'm not noticing it, eg: eliminates random toilets leaving 9,12,20, etc.
that Queue will fill up to max amount and afterwards oldest toilets ( whoever you enqueued first thru that method) will start to be Dequeued giving you reference and u destroy that
u cant do anything to random elements in queue even if u wanted
Is this a proper use of an animation curve to adjust the speed of a lerp?
_currentStrength = Mathf.L(_currentStrength, endValue, currentSpeed);```
you use the curve for *t* since the curve goes from 0-1 . . .
when a method returns a value how do you use the value
like after using
return;
and what is the value
the method is assigned to a value. just use the value after it is assigned . . .
can you give me an example
string name = GetName();
Debug.Log($"My name is {name}");
public string GetName() {
return "RandomDiscordInvader();";
}
So your saying evaluate t rather than recoil curve? Ah nevermind I'm not sure what you mean.
I can give u equivalent using list if u want access random elements lol
gimme a sec. let me find one of my uses . . .
it looks aight tho but multiply timeElapsed with recoilSpeed that would make more sense
Thanks no rush, Im trying to figure this out myself
t is is normalized from 0-1. you just put the value of t inside of `Evaluate . . .
@abstract finch when t moves from 0-1, the anim curve will move from 0-1 as well but along the curve you created . . .
not sure what you mean . . .
Ok Iβm trying to write code
And whenever I write it always sayβs Iβm wrong
Sooo
Iβve been thinking instead of just writing something randomly and hoping for the best
Or using someone else code cause thatβs weird
by t is it timeElapsed inside the coroutine?
Why not understand it first and know what I have to say to it
Like what they need to know
Inorder for them to take action
have you followed or watched a beginner or intro c# tutorial. sounds like that's what you need . . .
Iβve tried but I just get lost in the sauce
oh, i don't know anything about a coroutine, are you using that? i didn't see that code . . .
yep one sec ill post it its quite long
{
float timeElapsed = 0;
float startValue = _currentStrength;
float endValue = _currentStrength + recoilStrength;
while (_currentStrength < recoilDuration)
{
float currentSpeed = recoilSpeed*_recoilCurve.Evaluate(timeElapsed);
_currentStrength = Mathf.Lerp(_currentStrength, endValue, currentSpeed);
timeElapsed += Time.deltaTime;
yield return null;
}
timeElapsed = 0f;
while (timeElapsed < recoveryDuration)
{
float currentSpeed = _recoilCurve.Evaluate(timeElapsed) * recoverySpeed;
_currentStrength = Mathf.Lerp(_currentStrength, startValue, currentSpeed);
timeElapsed += Time.deltaTime;
yield return null;
}
}```
I can add notes to it if needed, to be honest i dont know what im doing here
that message is to me?
nah
oh sorry xd
ok ill give it a shot
since last night i got my 660 errors down to one π₯² anyone have ideas?? π₯Ί
here is an example. i'll look at your code right now . . .
_rectTransform.localPosition = Vector3.Lerp(_oldPos, _newPos, _animationCurve.Evaluate(percent));
percent is the normalized t you would normally have when using Lerp . . .
what is t exactly?
you will often see t used as a parameter for something that blends between two points
ranging from t=0 to t=1
Hey, anyone got an idea why the scripts on my prefabs are not updating when changing values and saving in visual studio? I also have auto refresh enabled.
I think the idea is that it's the "time" -- at time 0, you're at one point, and at time 1, you're at another point
You often see it in parametric equations, where it can quite literally be the current time
i see i guess the goal is recoil duration for me
okay, so you're adding to timeElapsed but you're comparing currentStrength to recoilDuration. if you're comparing those two, then you need to use both of those variables to get the normalized time and use that, or compare timeElapsed to the time you want it to take to finish . . .
theres two durations recoil then the recovery fro mit
Same for evaluating animation curves
since you often evaluate them with an elapsed time
oh man the typo is real im fixing it now
okay, that makes more sense . . .
to elaborate on how it works, there is two parts of recoil the move up part and pull back down, the reason why im using a global variable is so that if the player shoots again during recovery it will cancel the whole thing and start a new
it should be like this:
float timeElapsed = 0;
float startValue = _currentStrength;
float endValue = _currentStrength + recoilStrength;
while (timeElapsed < recoilDuration)
{
_currentStrength = Mathf.Lerp(startValue, endValue, _recoilCurve.Evaluate(timeElapsed));
timeElapsed += Time.deltaTime * recoilSpeed;
yield return null;
}
_currentStrength = endValue;
if you want to change the speed at which the lerp happens, multiply recoverySpeed by deltaTime. you multiply it by the evaluation of the curve. that will affect the interpolation . . .
ill give this a shot thank you!
also, you used _currentStrength in the Mathf.Lerp method, that will change the value of a every time it's called, thus, creating a skewed effect . . .
i'll update it with the speed change real quick . . .
ahh ok i have another cr thats doing this ill fix that too
now you can copy/paste and try it. i only did the first (top) half of it. you can try fixing the bottom half . . .
yea it pretty much works the same way
oops, i forgot to normalize the time. it should be timeElapsed / recoilDuration because what if recoilDuration is 5? it's supposed to be from 0-1 . . .
_recoilCurve.Evaluate(timeElapsed / recoilDuration)
i still dont understand the concept of normalizing when do you typically use it?
normalization rescales something to fit in a fixed range
How can I prevent an object I instantiated during play from being destroyed on application exit?
in this case, it remaps [0..5] to [0..1], which is what the Lerp function is expecting
you normalize to scale it to the 0-1 range. t is a normalized value for a lerp . . .
are you asking how to save your game?
everything is destroyed when the game quits..
so after 4 seconds, the t value is 0.8
how can you keep the object when the game quits?
I'm talking specifically about an inventory scriptable object which stores an array of item scriptable objects
At runtime I have an AddItem() fuction that instantiates a new scriptable object from a given item and adds it to the inventory
What happens when I exit the application is the scriptable object is destroyed
I want to preserve that object
you can't. everything is gone.
what you can do is write some data to a file
and then read that data back when the game restarts
and use that data to reconstruct your inventory
you need to save the inventory so you can load it when the application starts again . . .
I thought scriptable objects existed outside application instances tho
they do not
You are probably thinking of how you can make assets out of scriptable objects
those assets get loaded and turned into objects
you can't just create new assets on the fly or something, though. that's all locked in when you build the game
Anyone got an idea why script values are not updating on a prefab variant whenever I make changes in Visual Studio and save? I have auto refresh enabled.
Because they never do.
The values you see in the inspector are serialized in the prefab.
Gotcha, I think I understand it now
I'll look into a save system
The field initializers in your script are used when the object is constructed
The values are then overwritten as Unity restores the serialized values
So the field initializer only matters when creating a new instance of a component (or when you reset a component)
So how can I change a value in visual studio and have the updated value work in play mode? Because whenever I debug the value it is never updated
π Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
The value is whatever the debug says it is at the time you debug it
using Assets.Scripts.BaseClasses;
using Assets.Scripts.Models.BaseClasses;
using UnityEngine;
namespace Assets.Scripts.Models.Bullets
{
internal class ExplosiveBulletModel : BulletBase
{
public float ExplosionRadius { get; set; }
public ExplosiveBulletModel()
{
Damage = 1;
ExplosionRadius = 3;
}
internal override void SpecialEffect(PassiveEnemyBase enemyModel)
{
if (enemyModel.isActiveAndEnabled == true)
{
Debug.Log("ExplosionRadius = " + ExplosionRadius);
enemyModel.ExplodeEnemy(enemyModel, Damage, ExplosionRadius);
}
}
}
}
Changing the ExplosionRadius and saving, the script is attached to a prefab variant of bullet
okay, so ExplosionRadius isn't serialized, since it's a property and doesn't have [field : SerializeField] on it
I would expect it to always be 3, then, unless someone else is setting it.
Perhaps someone else is setting it.
It does have a public setter.
I mean when I change it in VS to let's say 2 and save wouldn't the field normally update in unity?
This isn't a monobehaviour is it?
BulletBase is
It has a constructor, isn't that not possible for a MonoBehaviour?
show BulletBase and tell us which field you're actually talking about
also yes you shouldn't use a constructor
Oh ok
that should be Awake
AFAIK the constructor will be run as usual
it runs as usual, but not when you expect
in fact it may run multiple times, and it runs before any serialized data is populated
right
using Assets.Scripts.BaseClasses;
using UnityEngine;
namespace Assets.Scripts.Models.BaseClasses
{
internal abstract class BulletBase : MonoBehaviour
{
public int Damage { get; set; }
internal abstract void SpecialEffect(PassiveEnemyBase playerModel);
}
}
not much here to really see
in this case, I would still expect it to work, since nothing serialized is being touched
I thought I remembered a warning saying not to do it. Which I guess is explicitly saying it is possible, just not recommended haha
neither class you shared has any serialized fields, so it's unclear which inspector value you're talking about
script values are not updating on a prefab variant
This seems to imply you're talking about some field in an inspector?
Can you explain which field you're talking about here?
and where you're changing it? And where you're checking it at runtime?
The explosion radius field here, I'm chechkng it at runtime
you're changing it where and when
In Visual Studio, it's never changing in the game
when are you changing it in visual studio
Right now? XD
as in, changing the values assigned in the constructor
that's not going to affect any already created objects
you need to use Awake and not a constructor
There are no serialized fields.
if you do that, it will change at runtime
Oooh wait, I get it
Those objects were already constructed.
Adding that to the list of reasons to not use MonoBehaviour constructors...
indeed - but the instances of those scripts in the editor do have that data, it won't be saved between Unity restarts though
or unloading the scene
yeah
long story short - don't use constructors for MonoBehaviours
If you need to call a parent class's "setup" method as well as your own, add a virtual method called OnAwake or something
and call it from Awake in the base class
Ok thanks, pretty new to unity, used to constructors
I've never used a constructor in a monobehaviour
ah, yeah, that also works fine
You can't use them for MonoBehaviours or ScriptableObjects in Unity
use Awake
Iβm trying to make it where only my hands show up for me in vr but to others they see the full body how could I do that?
is this VRChat
Disable the renderer for your body on your computer.
Enable it on theirs
Ok
Now the values are always 0 and 0 in the inspector
using Assets.Scripts.BaseClasses;
using Assets.Scripts.Models.BaseClasses;
using UnityEngine;
namespace Assets.Scripts.Models.Bullets
{
internal class ExplosiveBulletModel : BulletBase
{
public float ExplosionRadius { get; set; }
internal virtual void OnAwake()
{
Damage = 1;
ExplosionRadius = 3;
}
private void Awake()
{
OnAwake();
}
internal override void SpecialEffect(PassiveEnemyBase enemyModel)
{
if (enemyModel.isActiveAndEnabled == true)
{
Debug.Log("ExplosionRadius = " + ExplosionRadius);
enemyModel.ExplodeEnemy(enemyModel, Damage, ExplosionRadius);
}
}
}
}
run the game.
I did, still 0's
They will be 0 until the game runs. Use Debug.Log or the debugger, not the inspector
actually, you'll never see the values on the prefab, since it'll never get an Awake
you must look at an instance at runtime
How to keep an object as "visible" when partially obscured by obstacle?
Is there a reason you are using non-serialized properties like this? It seems very unusual to me.
You usually give an object serialized fields with a default value that you can then override in the inspector.
Weird it looks like the bullets from the object pool have the correct values, but whenever the bullet hits an enemy it still uses the 0 value's that show up in the prefab variant
now you're throwing in object pooling

sounds like your code has a bug then
if you're new to unity, you should be doing things in the most straightforward way possible
Well I know for a fact that I'm not changing the values anywhere in code besides the initial values
store values in serialized fields. instantiate and destroy objects as needed.
I need object pooling, I have a game with 100s of objects
100s is nothing
started lagging around 3k
that's not hundreds :p
of course, you should also be profiling to find out why it's lagging
Well I'm not done yet so I have to estimate for the future, rn it's hundreds, in the future prob will be thousands
it'll be zero if your game doesn't work
The game works fine, I think it's just unity not wanting to update my values whenever I edit a script, even though it did all the time before
didnt really see too much convo above, if these are objects with complexity (physics or some custom logic) then you just wont be running this at all. Pooling only saves you from new'ing up a bunch of objects, not from them actually existing
they're updating fine; you just saw the values in the inspector.
we've shown that the values are fine. if you have a problem with the damage being applied it's time to debug that
you figured out how to use the debug mode in the inspector - time to learn to use Debug.Log and/or your IDE's debugger
you should make sure that you aren't trying to call SpecialEffect on the prefab
rather than calling it on the instance of the prefab that hit the enemy
yep that's probably the issue
if you were using serialized fields instead of properties that get set in Awake, the prefab would have the values on it, at least
(although, it would still be wrong to be talking to the prefab instead of an instance in the scene)
Okay thank you, that ended up being the problem
Convert to mp4
Can you use IK with configurable joints?
Idk how to fix this
Are you switching your render pipeline asset in a script or something
dont thing so just clicked play was working before but I switched to this model and that happened
fixed the character turing pink but everything else is staying pink
I wonder if this being VR matters at all
I would make a new scene and see how that behaves.
{
public GameObject MainInventoryGroup;
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Tab)){
gameObject.SetActive(!MainInventoryGroup.activeSelf);
}
}
}``` no errors show, but the inventory screen doesnt pop up when tab is pressed
that would make the InventoryCheck turn off its own game object
you're affecting the GameObject this script is attached to . . .
give it a shot . . .
This is a question I'm having trouble describing, but its pretty much how to have object that I do visibility checks on behave as an obstacle for others but not for itself?
so you want it to block raycasts that you shoot at other objects to decide if they're visible?
Yes, I have it setup so theres a normal wall that just acts a barrier and when you it blocks visibility. The objects that are visible change colour.
I want the objects that change colour to also act as a wall for other objects that change colour
But becuase they're all on the same layer ("objects that change colour") I don't know how to make it ignore itself as an obstacle
you could turn off the collider before doing the check, then turn it back on afterwards
or you could use RaycastAll so that you get back a list of colliders
bro does anyone have any idea what could be causing this?? π₯Ί
Have you modified dotween somehow? I recommend uninstalling and reinstalling it
uhm it was missing so i installed the latest version of pro, i currently have only one error now π₯²
earlier it was 161
so uh im tryna do sum where i unlock the cursor to go into inventory but then lock it when i press tab again and my mind is dying tryna work the logic out anyone have ideas mb for being so slow lmao
{
if (Input.GetKeyDown(KeyCode.Tab)){
MainInventoryGroup.SetActive(!MainInventoryGroup.activeSelf);
Cursor.lockState = CursorLockMode.None;
if(invopen)
{
invopen = false;
Cursor.lockState = CursorLockMode.Locked;
}
if (invopen == false)
{
invopen = true;
}
}
}``` what i got so far, unlockes the cursor at first then doesnt afterwords
so just put Cursor.lockState = CursorLockMode.None in another statement
wym?
use else
Use else not another if
alr
u can do same thing with 3 lines if (Input.GetKeyDown(KeyCode.Tab)) { invopen = !invopen; MainInventoryGroup.SetActive(invopen); Cursor.lockState = invopen ? CursorLockMode.Locked : CursorLockMode.None; }
float timeElapsed = 0;
float startValue = _currentStrength;
float endValue = _currentStrength + recoilStrength;
while (timeElapsed < recoilDuration)
{
_currentStrength = Mathf.Lerp(startValue, endValue, _recoilCurve.Evaluate(timeElapsed / recoilDuration));
timeElapsed += Time.deltaTime;
yield return null;
}```
Is there a reason why this is instantly snapping to the end value without lerping at all?
nvm
Have you logged what recoilDuration is?
log the current timeElapsed and recoilDuration . . .
im not at pc but iirc animation curve can go beyond 1 might want to check if u didnt drag it around way beyond that
@abstract finchcs Debug.Log($"Time Elapsed: <color=cyan>{timeElapsed}</color> | Duration: <color=cyan>{recoilDuration}</color>");
can you use ik along with configurablejoints at the same time
yep I have its a local variable ive set it to 1 or 5 and the result is the same
alright
when I wanna do:
(myFloat > 0)
Should I use Mathf.Epsilon or -Mathf.Epsilon instead of 0 and why
Its progressing correctly but the lerp is just instantly snapping
send pic of ur curve
this looks fine. definitely show us your anim curve . . .
you really only need that when checking for equality . . .
Here it is
make so this thing maxes out at 1 and ur good to go, on both axis
your values are outside the 0-1 range . . .
that's also backwards. it will immediately snap to the end position then move away from it if they just reduce those values
ye
public class shooting : MonoBehaviour
{
public Transform firePoint;
public GameObject bulletPrefab;
public Camera cam;
public float bulletForce = 20f;
public float timeBetweenShots = 1f;
public void Awake()
{
cam = Camera.main;
}
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
void Shoot()
{
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
rb.AddForce(firePoint.up * bulletForce, ForceMode2D.Impulse);
}
}``` I'm trying to add time between shots so i can add customization to my gun but i don't know how
ahhhh
can i implement ik along with joints
store the time until the next fire in a variable and check if the current time is passed that time in the if statement when fire is pressed or in the Shoot method . . .
its working now thanks!
ok
Yo guys! In my game I switch between 3D and 2D and now in the 2D view it still feels like 3D (see screenshot). I change it by setting the projection to either orthographic or perspective. I might adjust it by setting the rotation of the camera to 0 if I press the key but how do I access it? This is my code:
{
_cameraRotation.yaw += _input.x * mouseSensitivity.horizontal + Time.deltaTime;
_cameraRotation.pitch += _input.y * mouseSensitivity.vertical + Time.deltaTime;
_cameraRotation.pitch = Mathf.Clamp(_cameraRotation.pitch, cameraAngle.min, cameraAngle.max);
if (Input.GetKeyDown(KeyCode.C))
{
use2DPerspective = !use2DPerspective;
Camera.main.orthographic = use2DPerspective;
if (use2DPerspective)
{
mouseSensitivity.horizontal = 0;
mouseSensitivity.vertical = 0;
}
else
{
mouseSensitivity.horizontal = 0.2f;
mouseSensitivity.vertical = 0.2f;
}
}
}```
The camera keeps moving itself, also when I switch back to 3D
I'd be glad if you can help me out
how would you hold a weapon with an active ragdoll character? with a normal character i would use IK but idk how to do that with joints. any advice?
more joints possibly? active ragdoll and weapons might be extremely tedious
you wont have a super nice way of forcing them to stay in position, if this is something like 2 hands on a gun for example
that's what i'm doing right now, a joint from the hand to the weapon but it's hard to control animate and aim
i want to spawn those spinning boxes on a plane, but i also want them to not be too close, so i wrote this function
private bool IsCloseToAnotherBox(float x_dim, float z_dim)
{
var boxPosition = new Vector3(x_dim, 0.5f, z_dim);
var colliders = Physics.OverlapSphere(boxPosition, 0.75f);
foreach (var collider in colliders)
{
if (collider.gameObject.tag == "SpinningBox" || collider.gameObject.tag == "Player" || collider.gameObject.tag == "Wall")
{
return true;
}
}
return false;
}```
it works most of the time but there is still some overlapping, the dimensions of every box is 0.25 and the draw sphere is 0.75 so there shouldn't be any overlapping. the screenshot shows the gizmos with 0.75 radius
the parameters come from this function, it keeps generating random values until the function returns false
private void SpawnSpinningBoxAtRandomPosition(GameObject plane, float x_dim, float z_dim)
{
GameObject obj = Instantiate(SpinningBoxPrefab, UnityEngine.Vector3.zero, UnityEngine.Quaternion.identity, plane.transform) as GameObject;
var x_rand = Random.Range(-x_dim, x_dim);
var z_rand = Random.Range(-z_dim, z_dim);
while (IsCloseToAnotherBox(x_rand, z_rand))
{
x_rand = Random.Range(-x_dim, x_dim);
z_rand = Random.Range(-z_dim, z_dim);
}
obj.transform.position = new Vector3(x_rand, BoxHeight, z_rand);
}
i hate var.... have you log the foreach loop and use comparetag instead?
what you want kinda depends how you want the game to feel. Like is this some game where shooting should be extremely accurate, or is it some goofy thing where the player just sprays around in whatever direction?
Maybe you can force the weapons rotation and make it kinematic? Honestly i was thinking of what to suggest and im blanking out because theres a lot of different stuff in here. Active ragdolls are more goofy/less accurate and weapons are supposed to be relatively accurate for a nice feel
oh i didn't know compare tag existed
so log every collision ?
it's kind of a goofy game
what i'm thinking is instead of the hands holding the gun
the gun holds the hands up?
first log the colliders.length , then log every gameobject in foreach loop (or use debugger)
every time there is only 1 collider, which is the ground
so they don't detect each other for some reason
nope the function returns true if it detects other colliders
maybe i'm wrong with the radius value?
even when they have .25 radius it still happens
itll probably be fine that the hands hold the gun, at the end of the day you'll probably get the same affect from either one. I think you could just attach it via joint and constantly apply a torque to your gun to get it towards the correct rotation
try overlap a large sphere after one box is spawned (put it outside the while loop, just overlap once), maybe cover the whole area, it must overlap the box
i tried running the same overlapsphere method after the while loop, and even doubling the radius from .25 to .5, and it still only get occational collisions with walls
but never boxes, even though they're closer than the wall
maybe i should try drawing box colliders instead? idk how to draw them though
onTriggerEnter() and onTriggerStay() are not multithreaded/multitasked methods, are they?
turn the radius of overlap sphere into 1000
just turn on gizmos then the collider will be drawn
Unless something explicitly says it is, assume it is not.
okay, i seem to be having an issue where both are being called, but i call Destroy() in onTriggerEnter()
i started getting about 290 collision logs
could it be that unity instantiation takes more than 1 frame or something
but the function isn't running in Update
like can there really be nothing wrong with the function because unity hasn't created a box in that position yet, so the function returns false?
https://gdl.space/ayuvowiyat.cpp here's my script
are you overlapsphere wirh radius 1000 immediately after spawnine all box (no waiting) then is successfully logs all the box? idk how unity physics works
i am trying to destroy the object as soon as it is picked up by the player if they are not on full health, but it seems that it stays around long enough for onTriggerStay() to be called, therefore giving me twice the intended healing amount
can onTriggerEnter and onTriggerStay called on the same frame?
yes i overlapped a 1000 radius sphere after spawning
i think on triggerstay triggers 1 frame after enter. you can set a variable to check with, there might be a better option idk
maybe try overlap a larger sphere while spawning (i have no idea why the sphere looks much larger than the box but it only overlapping the ground)
but once you overlapping a radius 1000 sphere, it works
i really hope it's not a unity bug with my version
i doubt it but i can't think of anything
maybe i'll try spawning them disabled, and then try to put them in the plane properly and enabling them?
If you're moving objects, those transform changes aren't immediately integrated, as that would be expensive. Calling https://docs.unity3d.com/ScriptReference/Physics.SyncTransforms.html would sync them in that case. If your call to Instantiate sets the position, I think that would set it before the new object is integrated. If you go through the transform afterwards, it won't update immediately.
private void SpawnSpinningBoxAtRandomPosition(GameObject plane, float x_dim, float z_dim)
{
var x_rand = Random.Range(-x_dim, x_dim);
var z_rand = Random.Range(-z_dim, z_dim);
while (IsCloseToAnotherBox(x_rand, z_rand))
{
x_rand = Random.Range(-x_dim, x_dim);
z_rand = Random.Range(-z_dim, z_dim);
}
GameObject obj = Instantiate(SpinningBoxPrefab, new Vector3(x_rand, BoxHeight, z_rand), UnityEngine.Quaternion.identity, plane.transform);
// Redundant: GameObject obj =
}
thank you! that solved the problem!
i was looking at the wrong function this whole time
i didn't think that the function not running in an update loop wouldn't make the changes immediately/on the next frame
i need to keep that in mind
which function is better to subscribe to events, awake, onenable or start? or does it not matter?
Generally Awake/Destroy or OnEnable/OnDisable. Consider whether the component can become disabled and how it should behave in relation to those events.
thanks
you are using an alpha release of 2023 so the chances of it being a Unity bug are quite high
should i use a lts release?
Always unless you really know what you are doing or need something very specific
got it, i'll install it soon
im still using 2021 lts, but there's no need to change so thats why im keeping it
"if it ain't broken don't fix it"
good plan, I still do a lot in 2019,4 and (mainly) 2020
some games like war robots (Pixonic) are still using 2017
yep, I still have a lot of 5.6 and 2017, 2018 projects
how would you get the vector of direction needed to look at something
Vector3 direction = (toPos - fromPos).normalized
To look at something you need a rotation, not a direction
what you probably really need is https://docs.unity3d.com/ScriptReference/Transform.LookAt.html or similar
{
if (target != null)
{
Vector3 lookDirection = target.position - transform.position;
cj.targetRotation = Quaternion.LookRotation(lookDirection);
}
}
would this work where cj is a configurablejoint?
what's wrong here? i'm trying to get the textmeshpro components from ScoreText and ScoreValue
getcomponents in children returns a single component
i know i could use GetChild(0) but i want to know what's wrong with what i wrote
are you getting the correct component?
are they UI or 3d text?
also, do you get an error or what?
and why are you using Find instead of serialized fields
TextMeshPro is for 3d text, not UI . . .
oh
i couldn't find a way to bring a component to another object so i just decided to find it in awake
i should have probably looked that up first
use TextMeshProUGUI or just TMP_Text (works for both 3d and UI) instead . . .
[SerializeField] private TMP_Text scoreText; and drag the object into the field
if you're trying to get components from child GameObjects, just use [SerializeField] and assign them from the inspector . . .
ah, i tried to drag the component instead
Both work but if you had the wrong type then obviously it won't work either way
it's cause you had the wrong component type, that's why it didn't work . . .
i tried to use serialize field but when i dragged the component, i couldn't make unity focus on the object i wanted, hovering wouldn't change the inspector contents, dropping it there just added a new component to it
You can lock the inspector contents with the lock icon
how would i get the component then?
open another inspector that's not locked
but doesn't really matter, just drag the object
what do i do when i lost date
how can i get it back
do not cross post
does someone know why when i buid a project 2d for android the game look like it would have 30 fps? Its just a flappy bird... so the game its quite simple
30fps is the default for mobile
how can i increase them?
it looks horrible
The jump of the bird looks weird and not very fluid
I doubt it's a frame rate problem. Frame rate doesn't/shouldn't cause changes in how objects move
In my computer its quite soft the movement
it will, the higher frame rate, the objects will move "smoother"
If only the bird looks weird and nothing else then it's not a frame rate issue
other than maybe indirectly
all objects looks weird, but specially the bird...
So, i just need to create an script and paste this? ```cs
using UnityEngine;
public class Example
{
void Start()
{
// Make the game run as fast as possible
Application.targetFrameRate = -1;
// Limit the framerate to 60
Application.targetFrameRate = 60;
}
}```
and drag it for example into an object called fps controller
apparently this makes u jump up higher if u hold down for longee, but how does it work?
also what button is ('Jump')?
i remember the button is setted in project setting
edit > project settings > input manager
so if the game was published would my selected input be the same for everyone else?
or would it vary depending on the other persons selected input
that will not make you jump higher if the button is held down for longer. GetButtonUp only fires when you release the button
To solve my fps problem i just need to do what I said a few messages abobe?
.
well then it technically does as when u let go, it sets ur velocity to that value causing u to fall, so if u hold for longer before letting go, then u will go higher before getting that value set on ur velocity right?
this is the whole thing
its basically from a character controller script
steve smith thanks for the help u helped me understand now
do you think that will work?
no
neither do I
well it's wrong. It's missing something absolutely crucial
What is it?
don't you see it?
what does a class need to have if the Start method is to be executed?
exactly
and that will work correctly?
maybe, try it and find out
just one thing, why i would like to limit fps rate?
conserve battery power, stop overheating for 2 reasons
Stopping unnecessary hogging of the GPU. Often uncapped framerates will also cause unpleasant coil whine noises from GPUs
30 fps is not janky so I'd be surprised if that solves the problem but if it does then great
depends on how well/badly it's been implemented
@dry tendon One thing you could try is to limit your fps to 30 on your computer and see what happens to your game
thats exacly what i thougt
now i say you
ok, so
in my computer that limit works
now i'm gonna build it and see what it happens
Sometimes the OnMouseDown/Up command work and sometimes they don't
although the scripts are very similar in both cases
Yes I have checked allignment and collider/trigger
i need help
on how i can have my particle system on play while the player is running
how do u move ur player
set the transforms position to a vector3
how bout meee
oh I was asking bloo how does he moves the player but actually it doesnt matter u should have running bool then u like
in the update method, check if they are running and play the particles
var emission = urParticleSystem.emission;
emission.enabled = running; in update and it should work
Particles systems have an emission rate over velocity module. Tweaked right, you shouldn't need to program anything in C# to make it work
yeah i do that then it only plays AFTER i stop pressing the key for it to run
oh i dont have separate
just running
then its just when moving and theres "rate over distance" in ur particle system
Even if you have multiple walking speeds, you can use a curve for the emission rate
how does the emission rate over distance work
so i just keep it on loop
and start on awake
Aside the field where you input the value, there's a small dropdown where you can select between "single value", "random between two values", or "curve"
okay imma continue this after dinner
oh dayum
ty, ur gonna make sum taiwanese exchange students happy
I got a slightly weird problem? I'm trying to create a good ol' Singleton. This is the awake function for it:
void Awake() {
Debug.Log("This first?");
if (Instance == null) Instance = this;
else Destroy(gameObject);
DontDestroyOnLoad(gameObject);
}
Then on another script I'm trying to call it OnEnable.
void OnEnable() {
Debug.Log("Hello");
Singleton.Instance.DoSomething();
The problem is, Hello comes out first? Its very weird? I also changed the ScriptExecution order for the Singleton to start sooner.
Any ideas why that might be happening?
OnEnable executes before Awake, Also your Awake code is incorrect
What. No it doesn't.
You sure?
Awake and OnEnable run sequentially yes, it's not like Start and Update
But Awake is first
Not "all Awake", then "all OnEnable"
is the singleton already in the scene before playmode?
same object awake->onenable->other object...
Sorry I missed the 'Other script' bit
Yes. As are the obejcts calling the onenable in this case.
use Start if u want to be everything ready in other scripts I think
Awake, initialize yourself. Start, get refs from others
I spawn objects in at runtime via a pool. Some objects are in at runtime, others need to fire with OnEnable.
This is just the first time this is happening to me.
That way everything will always be initialized at the time you start getting references from other objects
Anyway the Awake is still wrong
Instead of just saying its wrong you could explain how its wrong.
Potential DDOL on a Destroyed object
bruh I was looking at it and was thinking why as well the fact Destroy isnt "return" out of method still gets me 