#💻┃code-beginner
1 messages · Page 422 of 1
can u help me doing it cause i dont understand it tbh
The page has code examples even
guys there is a green health bar and shield bar down of it
when ı change shıeld slider value it changes x scale
ı want to delete part and part
anyone knows?
The easiest way to make a health bar is via the UnityEngine.UI.Image component’s fill mode and fillAmount value. https://docs.unity3d.com/2019.1/Documentation/ScriptReference/UI.Image.Type.Filled.html
my englısh not enought to undurstand this.. But ty
do you know spanish or german
no just turkish and little bit english <3
ok
I have a script set up to animate a gameobject upon a mouse click, the coroutine gets called but nothing changes in the animator ```public class SwingAxe : MonoBehaviour
{
public Animator Swinger;
public bool Clicked;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
StartCoroutine(AttackAnimation());
}
}
IEnumerator AttackAnimation()
{
Debug.Log("Clicked");
yield return new WaitForSeconds(1);
Swinger.SetBool("Attacking", true);
new WaitForSecondsRealtime(2);
Swinger.SetBool("Attacking", false);
}
}```
i have a screenshot i can send too
you missed yield return where you create a new WaitForSecondsRealtime
aight
let me test that
thanks man
that was such an easy fix
i kind of feel bad for asking
so i have this code that spawns cubes randomly across a certain range and sometimes it spawns 2 cubes in the same spot how do i prevent that
can i call someone who can help me via Call. I have many problems and the DeadLine is in 5h
like its so simple shit but i fail miserable
save the generated positions in a List and check if they already exist
do you know how to make and use a List ?
not really i started unity 2 days ago
https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=net-8.0
this is why Google exists
everytime i throw a shuriken it get instantly deleted and idk why
what
what is a vector3 considered as
cz i have to specify the type of the value in a list
List<int> numbers = new List<int>();
int or float?
yes and Vector3 is a Type
List<Vector3>
Better to round the vectors and store them as Vector3Ints
Theres a very small change that your Vector3's will be exactly the same, so rounding gives them some "spacing"
!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.
You can multiply the vector before rounding if you want a spacing different than 1 unit
Sorry, just noticed that you are already using ints for the vector and not floats 🤦♂️so it might not need to be rounded
how do i check if randpos im about to add to the list is already there?
use occlusion culling otherwise itll start lagging when u add more objects in the future
its not related to ur problem btw
jst advice
List.Contains
But a HashSet would work well here too
sort out your usage of List first, atm it is incorrect
Yeah, it is using a different local list, not the list in your class
and it's creating a new one every itteration
Yikes . . .
so whenever the loop restarts all the items are cleared in the list?
you create a new one so, yes
no, why not use the pos you already have?
wdym?
the pos at the top is not the same as the pos at the bottom
Do you need pos outside of the Start method?
no
then remove the one at the top
i ùeant 2
okayy tysmm
now to check you would use pos.Contains
wait it wouldnt work
all the vectors in the list are named the same thing
how would i check if one of them equals a certain value when all of them are the same name
vectors don't have names they only have a Type and properties
you are comparing one instance of a Type with another instance of the same Type
so im comparing the properties?
That is just the name of the variable. It is not part of the variable's data itself
no, that is a variable
yeah ik im storing variables in the list
if (pos.Contains(randpos)) { }
does the values of randPos exist in the list of Vector3's ?
why in gods green earth is this an error
because you have 2 possible versions of the Random class
this is why we use IDE's, hover over it and it will tell you
i used this
it told me to specify
for example it said do System.Random.Range
that also didnt work it told me range isnt a thing
or.. UnityEngine.Random.Range
it worked when i did UnityEngine.Random.Range
yeah ik
u can also do using Random = UnityEngine.Random; at the top
yes, you have 2 different possible Random's. System.Random or UnityEngine.Random, you must chose which one to use.
The easy option is to add
using Random = UnityEngine.Random:
then Random.Range will just use Unity's
ohhh so i have to specify
tyy
try it out
You literally said it told you to . . . 🤦♀️
<#💻┃code-beginner message>
you could have also just removed the system using directive since you aren't even using it
how do i fix that
private Vector3 lerpTowardsPosition;
private Vector3 velocity;
[SerializeField] private float speed;
[SerializeField] private GameObject[] wheels;
private void Awake() {
lerpTowardsPosition = transform.position;
}
private void Update() {
transform.position = Vector3.SmoothDamp(transform.position, lerpTowardsPosition, ref velocity, speed);
foreach (GameObject wheel in wheels) {
wheel.transform.localRotation = Quaternion.Euler(0, -90, velocity.magnitude);
}
}
public void goToLocation(Transform newLocation) {
//transform.position = Vector3.Lerp(transform.position, newLocation.position, 0.5f);
lerpTowardsPosition = newLocation.position;
}
I have an object rotating around the center during runtime, not the pivot. is there a box to check to fix
how have you confirmed that it's pivot point is not its center
first pic is pivot view second is center view
the Center tool handle position has nothing to do with how an object rotates. it shows the approximate center of the selected gameobjects
if i had to guess, you are probably rotating this object's parent rather than the object itself and the object is offset from the parent such that when the parent rotates it appears as if the object is rotating about its center
Whats wrong with the raycast origin and direction?
https://hatebin.com/tuzwjzwcii
your parameters are incorrect for your Debug.DrawRay call
how do i move a capsule using a rigidbody
im trying to make a reference to the text of an Input field, but im not sure what to call it
public InputField NameMaker;```
lots of options in the Rigidbody documentation
simplest would probably be Rigidbody.AddForce
the brackets are the spot where im not sure what to type
istg i clicked it earlier it gave me one line of code and didnt even explain
string?
Did you read the description
i tried that, but then i cant use it later
here ill give an example
ok
so it suddenly works when i try and show poeple
thanks unity
That wouldn't be a Unity issue, code is code.
You can use it wherever you want, assuming you use it correctly. Which, if it didn't work before is because you didn't use it correctly.
okay so now my capsule flies when i hold space
how do i make so i only jump when im grounded
triggers
i started 2 days ago what does that mean
you really should follow !learn to save you from a lot of this shit
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
hi everyone, i have a question so basically, how do i know if i need to create a new scene? for example, i am developing this game which had this 2 different scene, the shed and the backyard, the player would occasionally go back and forth between these two place to pick up items, is it better if i make these 2 in different scenes or just in 1 scene?
either option is perfectly valid, it really depends on how you want to handle it
ah okay! thank you so much, i thought i was doing something wrong
this script is making my project being unable to build, why? Its just an util
using UnityEditor;
using UnityEngine;
public class RectTransformUpdate : MonoBehaviour
{
[MenuItem("CONTEXT/RectTransform/Snap Anchors To Corners", priority = 50)]
private static void Execute(MenuCommand command)
{
RectTransform rectTransform = command.context as RectTransform;
RectTransform parent = rectTransform.parent as RectTransform;
Vector2 parentSize = parent.rect.size;
Vector2 parentMin = parent.rect.min;
// Find corner point coordinates in parent's local space
Vector3[] corners = new Vector3[4];
rectTransform.GetWorldCorners(corners);
corners[0] = parent.InverseTransformPoint(corners[0]); // Bottom left
corners[2] = parent.InverseTransformPoint(corners[2]); // Top right
Undo.RecordObject(rectTransform, "Anchor Modification");
rectTransform.anchorMin = new Vector2((corners[0].x - parentMin.x) / parentSize.x, (corners[0].y - parentMin.y) / parentSize.y);
rectTransform.anchorMax = new Vector2((corners[2].x - parentMin.x) / parentSize.x, (corners[2].y - parentMin.y) / parentSize.y);
rectTransform.sizeDelta = Vector2.zero;
rectTransform.anchoredPosition = Vector2.zero;
}
[MenuItem("CONTEXT/RectTransform/Snap Anchors To Corners", validate = true)]
private static bool Validate(MenuCommand command)
{
RectTransform rectTransform = command.context as RectTransform;
return rectTransform.parent != null && !PrefabUtility.IsPartOfImmutablePrefab(rectTransform);
}
}
you can't use editor code in a build, put that into an Editor folder or wrap it in preprocessor directives
because it uses UnityEditor code which is not allowed in a build
ok so it goes into Assets/Editor ? or where do you mean
It worked, thanks !
Hey so i'm planning to use a DDoL to keep the "user" string safe between scenes, yet I dont know where to put this DDoL. Can anyone please help
public InputField NameMaker;
public void NewGame()
{
Main.SetActive(false);
Username.SetActive(true);
}
public void UserChosen()
{
user = NameMaker.text;
}```
nowhere there. Perhaps share the full !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.
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class ButtonScript : MonoBehaviour
{
public float NewGameCheck;
public GameObject Main, Username;
public string user;
public InputField NameMaker;
public void NewGame()
{
PlayerPrefs.SetFloat("NewGameCheck", 1);
Main.SetActive(false);
Username.SetActive(true);
}
public void UserChosen()
{
user = NameMaker.text;
}
public void NewUserHitPlay()
{
PlayerPrefs.SetString("Username", user);
}
public void Continue()
{
PlayerPrefs.SetFloat("NewGameCheck", 0);
SceneManager.LoadScene(1);
}
public void ExitButton()
{
Application.Quit();
}
}```
please actually read the bot messages
sorry, i didnt think 39 lines was too many
6 - 10 lines is too many
Anyway you need an Awake method and DDOl in that
one last thing, what would i say to DDoL
obviously the user
but how would i type that? should i try first and post errors here
In awake
You should google the method and look at the example code, which will tell you exactly how to type it
I'm a complete beginner and these two errors show up, why is that?
first !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
also you're passing two positions
you cant turn a vector3 into a quaternion
I mean, you can using the methods that do it for you
well yea but i mean the way hes trying to do it
its because they are passing two positions so its reading the second one as the rotation
edit: https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
I know, but best to be clear, especially for beginners
alright
To be clear about what you are doing. You wrote:
Instantiate(object, random position, other position, rotation)
See the declaration that navarone provided
ok so i have this:
{
DontDestroyOnLoad(user);
}```
but its telling me i cant convert string into an object
what is user ?
you can't DDOL a string
yeah so how would i attach the string to an object
You were supposed to DDOL a component that has the string in it
rip
https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html
see the DDOL expect an Object
It is already "attached" to the component since it has the string variable. Now DDOL the component
but what component would i use
It could be one that you make
Do you know what a component is?
Is InputField.text a component?
i know it isnt
I would start by creating a separate gameobject and component for persistent data
So why did you try to DDOL it
because its worht a shot
i saw that line in a tutorial
"Close enough" is not going to work in code
you need to pay more attention to the code you copied, and also get your !IDE configured
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 170
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2024-07-12
i nevr said close enough
If you knew that:
- DDOL needs to be called on a component
InputField.textis not a component
What was the thought process to call DDOL on InputField.text
I didnt watch the video, but dont multiply mouse input with deltatime
fixed
And make mousesens way smaller after that
its low at 100 tho
Now that you dont multiply with deltatime (which is a small number) you need to account for that
So the sens should be made about 50-100x smaller
hey what function should i use if i want my code to get called only at the beginning of the game and after switching the scene?
well Awake and Start always run one time on each object in the scene when it loads (if gameobject is not disabled)
yeah i tried using awake but it didnt work
what "didn't work"
idk what that means
i wanted to setActive on my canvas to false, but it didnt work as it was still visible
are you talking about a DontDestroyOnLoad object?
what is a DontdestroyOnLoad object?
If you don't know what that means, then you probably aren't using it and Awake will run on scene change
it works on scene change somehow i tested it with a debug.Log
Awake runs every time an object is created. If you aren't persisting an object between scene loads, every time a scene is loaded, all of the objects in it are created
So Awake will run on scene load
when u load a new scene DDOL objects remain
why am i unable to rotate left or right
you realize no movement is being applied anywhere
Probably, because I don't see you changing the character's position anywhere
You mean rotate?
Because the global variable is used instead of a local one
so change to private?
I suppose, xrot is -90 the whole time, and the mouseX just decreases it before clamping again
A global variable is a variable, created not directly inside of the method
This means, the variable stays persistent throughout the Updates
he sets his local transform rotation and then calls Rotate on the playerBody transform we're lookin at his head script
Minor terminology correction: That would be a field variable.
If you wanted to look it up that would be the term the documentation would use
so what would i change
I see, the global one is in a static class
if anything a Constant is more of a global no?
Create xrot directly inside of the Update method
I think of both static and const as "global"
true static field can def be "global "
now i cant rotate at all
i can rotate y just not x
i thought they were just called fields or instance variables, i've never heard field variable
which one Body or transform
body ig?
Simply remove this variable and use the Transform.Rotate method with mouseX and mouseY as first 2 parameters
Is your rigidbody's rotation constrained/frozen
If you even have a rb
no rb
im just moving main cam
ok but i dont think my canvas is DDOL object
How can you even rotate the y axis, if you're constantly setting it to 0?
i'm working on a project that generates objects that a square bounces on. my current code generates objects correctly, but there's an issue that makes it so that an object can spawn on the intended path of the square, which makes it so that the object knocks the square off-course. what do you guys think i should do to fix this?
Don't spawn it there?
okay so i didn't provide enough info because i didn't want a wall of text, let me rephrase
are you starting the next scene with the canvas already enabled
That's what you should do if you don't want to receive an answer like the one I've provided above
Check if the position of where you trying to spawn is within the path area
Technically they're just called fields but can be referred to as "field variables" to specifically differentiate from "local variables"
yeah i think so as it is enabled before switching
i am making a software to generate one of those "bouncing cube" videos that you see on short-form content where the cube hits the wall according to music. i have my code parsing each note from a midi file and figuring out when the cube should hit a wall. the issue is, sometimes, the correct generation of the walls to the beat of the music makes an object spawn in the path of the cube previously. this is all generated before the cube even starts moving. i'm trying figure out how i can figure out where the cube will have travelled by the time it reaches a certain wall so i can prevent walls from spawning in the way of the cube's path. here's a video showing the issue. you can see in both runs, the cube is knocked off of its course because it hits an object that it was meant to hit later on. the red lines show the intended course.
is that better?
I'm talking about in the new scene?
it doesnt exist in the new scene. but when i switch back to the old scene its still enabled
not enough info just by this video. Sure we see the problem but we have no clue how you even genertate anything in the first place, (code) how can we know of any suggestions besides the "just dont spawn it there"
well yeah things reset on scene change, they are technically brand new objects.
does it already start enabled the first run of scene?
no
unless you specifically told it to preserve state, aint no way it would stay enabled on its own
i think it lives
or user error **
well either start showing the setup and script or we can just go in circles speculating
the method is like 100 lines long and nobody wants to read that. even just the relevant part is 50-ish. i'm just asking how i could store all of the locations that an object would have theoretically been if it had a certain velocity. i know i could literally just make a giant list and populate it with all of the locations, but that seems inefficient and there's likely a better option.
if you really want to see the code, here's the hastebin
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
no clue why it saved as java :(
Which are the specializations in game programmer field?
cause c# is pretty much very close to java
so you're talking about storing like a predicted position/path on the way?
yeah
the entire thing is generated based on where it predicts the cube will be if everything goes right
yeah i fixed it like a real mf. i think its because the variable GameOver is still true after switching so i copied a prefab using setting the value and disabled exploding, falling, or anything else except setting GameOver to false in awake. dont hate me i just want this project finished
you made a singleton ?
Why is my trait variable also being changed?
ResourceType trait_k = new ResourceType();
trait_k = trait;
Debug.Log(trait.resourceAmountShallow);
trait_k.resourceAmountShallow = 0;
Debug.Log(trait.resourceAmountShallow);
Am I not creating a new variable trait_k and changing that one instead?
The 2 debugs print different values
reference types its the same object, you're not cloning it with =
you can make it value types if its just numbers
yeah but i couldnt set it in other scripts idk why so this was the faster method which im never gonna use again and just bc i have to finish the project untill tomorrow
like I said if you only deal with numbers in your class, just use a struct
they always give you a copy
should fine
But if not how would I copy a class?
for example you copy the values over to new instance instead of assigning the same instance
you could potentially also look into https://learn.microsoft.com/en-us/dotnet/api/system.icloneable?view=net-8.0
or deep copy
ik this may sound stupid, but how do draw a filled circle in unity 2d
public MyClass(MyClass other)
{
Id = other.Id;
Name = other.Name;
}```
`var myclass = new MyClass(otherObject)`
for example of the first thing I mentioned, make the constructor get the other object to copy
alright, ill try
i saw a guy use a DrawCircle(vector2 pos, radius, colour)
If that's what you saw, then that's a function they made
That's not built in
yeah like
That's not a debug circle
It's probably better to just use an image
so
how to draw a mesh in unity and go from there
this is how reference types work. a variable with a non-primitive type just refers to the actual object instead of storing the object. this means that if you make another variable equal to the reference, you have two variables pointing at the same thing.
ight then ill try that thanks
cus i am trying to create a particle fluid simulator
I am making a scrollable menu with different slots(which I made prefab) but the thing is that there isn´t going to be a specific number of them. These slots are the receipts the player learns throughout the game
how can I make this menu if I don´t know how much slots are there going to be??
thats like..very complex..
goodluck lol
ikkk ill see
there was a contest size fitter I think ?
idk this UI stuff much
i spawn all the items in code though, each UI item has a prefab that gets spawn as child of scrollrect then added the content size fitter it automatically expands
What part are you uncertain about? This just sounds like a for loop to me for adding each receipt as a child object
Instantiating them?
or how
Yes instantiate is how you spawn things
var item = Instantiate(uiPrefab, theContentOfScrollRectTransform)
if you keep destroying and instantiate it creates garbage
ideally instead of destroying you recycle
(Object pooling)
Oh, okay, I see
you should not worry at this UI level. How many are you really doing ?
realistically, this is better applied when you keep spwawning something like Bullets, enemies etc.
can you make a prefab for a circle sprite and instantiate as a draw circle
can that work?
thats literally what they suggested #💻┃code-beginner message
but idk how you would apply that to fluid sim
are you spawning a whole bunch of small circles to simulate liquid? ig it can work that way
yep
i see. yeah thats not too bad
there are ways with particle system and would prob give better performance but thats way more math heavy
#💻┃code-beginner message
There is enough info.
Trying to figure it out right now, but it is hard to come up with a solution, which doesn't decrease the performance too much, when more obstacles are added.
You could store the spawn positions in the list, and then enumerate through the whole list to look for any unwanted intersection points between the position pairs and the previous with target positions
But it's not going to be efficient
i have 2 audiosources on one object and im trying to control both volumes with a slider. i made a script but how can i access both sources bc if i drag my object (where the sources are attached to) into my 2 public audiosources its 2 times the same source
drag in the specific Component directly, not the gameobject
but i cant bc i dont have two inspectors
wdym you dont have inspectors
you literally just said
bc if i drag my object (where the sources are attached to) into my 2 public audiosources its 2 times the same source
i dont have two inspectors*
pop and lock it 🕺
oh ok ty
@obsidian granite
Haven't worked with Meshes, but, I suppose, you can create the character's path by adjusting a single Mesh's verticles using the newly selected positions, and check whether the target direction intersects it. If not, this is a suitable one.
This should be better than storing them all in a List
i read that as, "pop, lock, and drop it . . ." 😆
Apologies if this isn't the right channel for this question, but I'm wondering how I can implement a house with a door in a metroidvania, where the inside and outside of the house both occupy and show the player's location as the same spot, but going inside the house changes the map to show the inside instead of the outside. Preferably, this is all done in a single scene
place the audiosources on separate GameObjects . . .
same lol
great minds . . .
Unity Inspector: Krunk Edition
Hi. I have a question: How can I change the text, leaving it as it is now, but add another string to it.
There is a string = I love you: 0% We are doing something and 0% is changing to other numbers:
I love you: 100%
Of course, it will be possible to write letters in the inspector first, and then write +float in the script, but if the language changes?
How can I change the text by simply adding a new string, leaving the old one?
Can you provide an illustration of that intended outcome?
Unfortunately, I'm out atm and can only provide the full size map. It takes a bit to load and may be hard to see but if I point to you the exact area, would that work?
store "I love you" and the value in separate variables, then combine them when you assign the text, like . . .
text = $"{ILoveYouVariable}: {valueVariable}";
You could also just have 2 different texts
Anything might help :P
I just couldn't quite grok what you are describing... My best interpretation is that the interior of the house is separate from the external world-space (so like rabbit hole buildings - the interior could be could like be a different size than would actually fit in the exterior as rendered), and you have a minimap of the exterior environment which displays a marker for the character on the house?
@split dragon yeah, you can have 2 separate ui text GameObjects and align them . . .
string label = "I love you: {0}%";
string.Format(label, 100f);
Yes. Of course, it can be done this way, but if I change the language, then there will only be letters
What does changing the language have to do with anything?
Yes, I have already done everything here and it will be difficult now to do 2 texts everywhere(
why not use Localization package
sounds like you want localization . . .
mate. don't crosspost
Again, apologies for any clarity issues. The picture does take some time to fully load
sry but i am stressed since it wont work
i use her
Well, look. Let's assume. that we have a slider and a text that changes from the value of slider.value: "Viewing range: 300." If I change the language, then there will only be letters: "Viewing range: ",because it is written that way
and that means what ? everyone has their own issue they want to fix, no need to break server rules n crosspost
i am sry i reget it
its fine lol just a heads up for the future
yea well i dont know how this google play games work
no clue I dont use google play
look into string formatting in c#
Honestly I have no clue what you mean. This just sounds like a logic issue. Like why isnt it always appending the number when its displayed?
"Its written that way" well write it differently
@raw token Here's a better focus, and hopefully they're easier to see
did you even bother looking at this before uploading it?
Yes, I'm aware of clarity issues. That was stated above.
I'm no pro, but just spitballing: you could position you interiors in some far-flung corner of the scene (or separate scenes with additive scene loading) and have your doors keep a reference to their paired counterpart, and maybe like a flag indicating if the door is an interior or exterior door. On interaction with a door, teleport the player to the corresponding door, and if they've entered an interior set a flag on the player indicating that they are now in an interior.
Maybe use a property on the player to expose their "overworld position." If they're not in an interior, it would just return their world-space position, but if they are in an interior it could return their last known world-space position. Render their position on the minimap based on that property.
You could maybe make it all more robust by explicitly describing interiors, maybe with like a Scriptable Object asset, or a script on the interior's root object. This way the interiors could be definitively associated with specific "overworld positions," and doors/portals could inform the player about the attributes of their current interior
Anybody knows what is going on here?
Severity Code Description Project File Line Suppression State
Error (active) CS0246 The type or namespace name 'SceneAsset' could not be found (are you missing a using directive or an assembly reference?) Assembly-CSharp.Player F:\Unity\Broken Wings\Assets== Codes ==\SCK\GridManager.cs 25
I could get back to string or scenes ID but I like to drag and drop stuff on inspector 😁
any pointers on how i can get the player to rotate with the platform? i tried parenting the player movement to the platform as ive seen others suggest and it doesn't work it kinda just gets stuck when i do that.
Parent the player to the platform
read what i just said
why does it gives me an error? im pretty sure i set the variable. https://gdl.space/hutotozare.cs heres the code where the error occures
can i change the base scale of a sprite ? like before dragging it in the scene
or hierarchy
Counter is null
As an after thought, you could also actually store the interiors in the same x/y space as the exterior but at a deeper z depth. If you lined up the doors, this might let you relatively easily pull off some neat transitions within the same scene... though that might get finnicky in some situations
Don't know why you circled a completely different script though
this is a picture of the wrong script . . .
the code provided is from CanonMain . . .
but the inspector image shows Projectile . . .
In the update method do this player.transform.rotation= platform.transform.rotation.
hey im a 3d designer and i wanted to work on a project with people for my practice so i would pretty much make u free 3d assets, which channel can i go to to advertise this?
will do 👍
the unity discord does not have such a channel . . .
okay thanks ill go somewhere else 😅
Yes we could see that in your first images. counter is null. Where do you set counter on CanonMain?
the image you linked is from the Projectile script. make sure counter is assigned in the CanonMain script . . .
it is
This will only rotate the object, not actually move it along with the platforms rotation.
- is
counteran int - can an int even be null
the error says otherwise . . .
im a bit brainrotted right now haha
it is your script; it is your variable . . .
🙃
the Z depth is genius. Then this way, the xy is functionally the same, and the basements could be on the same Z axis so a screen transition isn't needed for the basement, while the player marker is in front on a higher Z axis so it's always visible. Is this what you mean?
@hallow acorn line 10 of the script you provided. that variable is not assigned . . .
oh yeah i assigned it at the brefab but actually the prefab is never used bc the firepoints where the canonmain script is attached to are different object idk why i made this prefab lol
assigned it to the actual scripts and it works now
Does anyone know why my player runs faster when running diagonally, or pressing W and D or W and A? https://hastebin.com/share/masokinimo.java
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
normalize your move direction before you multiply speed
The suggestion you were given doesnt even make sense given the question. This problem isnt as easy, you need to calculate how far to actually move the object on top of platforms each time the platform moves.
You should have some way of combining movements before actually moving your player. So you would basically be adding like the movement from input and external forces (the platform). You might be able to just use the local position of where the player is on the platform to start then calculate deltas. Though I dont know an exact solution, was just trying to tell you the other one wasnt even a solution
You mean normalize(), on desiredMoveDirection?
well thanks for not making me waste my time with that at least.
I actually hadn't considered how that would affect the minimap 😅
But I definitely think it's an interesting possibility that would be fun to explore though. The tricky bits I envision are that 2D collisions don't care about z depth, so the interiors would probably need to be inactive until the player enters them, and maybe like input locked for the duration of the transition animation. The trickiest bit may be cases where an interior has multiple portals which cannot all be aligned with their overworld counterparts simultaneously
I'll take this all into account. Thank you for helping good sir! I'll test this out and see how it works out
Cheers! 🍻 I'd be interested to hear how it develops
private void FixedUpdate()
{
velocity.y += (-9.81* GameManager.Instance.deltaTime) * timeScale;
transform.position += velocity;
why is this going so fast? have i messed something up here
Math looks fine to me - only weird bits I see are if GameManager.Instance.deltaTime does not reflect Time.fixedDeltaTime, or timeScale is nutty
GameManager.Instance.deltaTime is 0.01666666
1/60
Did you debug what all the values are? Also does the velocity.y ever get set to 0 because this code shows that its only added to constantly
0 meaning like when its grounded
why using 2 different time variables for essentially t^2
Looks more like it's a custom time scale for this object, which itself is valid. It being 1/60 though is kinda weird
im not doing any grounded stuff, im just messing with velocity using a fixed point system
wait
timeScale is 1
deltaTime is 1/60
sorry i miswrote
Still, have you debugged anything related to this?
yeah, it seems to be fine, one sec
If you arent setting it to 0 ever, what's stopping objects from accumulating velocity while standing around
im just testing stuff right now, im literally rewriting the system from scratch
FixedUpdate() likely won't be executing at 1/60s intervals unless you've configured it as such, for what it's worth. But I would think that that discrepancy would slow things down instead of speeding them up
i've configured the fixedupdate timestep to be 1/60
you are both += the velocity and also += the position
idk if you can read thsi
🤷♂️ if the values seem fine and you're having an issue, then you've likely not shown some code
isnt that how youre meant to do that?
are the values fine though?
This isn't the issue, please dont guess at stuff
How am I supposed to know? I told you to debug it
it appears to be moving the position by the velocity each frame. is that normal behaviour?
Ah wait... Your change in position should be multiplied by the time
so both of them or just the position?
dv = a * t
dp = v * t
Both
"p" for position, while intuitive, somehow just sits wrong with me
oh yeah there you go
I'm too physics-y based to think "momentum" there
hahaha yeah 😅
It's been a while since I took physics. I'm sure there's a more... appropriate symbol
ddisplacement? dtranslation?
What
works now, thanks! i can start working on other things now
I just typed "x" and
"dx" would be a change in position
(strictly, "x" should be in bold or underlined, if it's representing a vector)
But I'm amazed that the server moderation considered that an inexpicable phrase here
I'm not sure what kind of school taught you that
I really need to take some dedicated time to go back and study physics and calculus again, now that I actually care about it
I said "strictly"; in practice if it's contextually understood that x is a vector, than adding extra labelling to it is kind of erroneous
...If needs be, I'm British
I understood what you wrote, but underlining or bolding is definitely not convention, anywhere
The only notation I've seen is a line above, which my upper year profs didnt even enforce because no one understood wtf he was doing anyways
I'm coming at this from a maths perspective; I'm aware other disciplines use different conventions
That might have caused this confusion
Heck, I'd be confused by this as well, because it'd look like a statistical mean to me
Btw, unrelated, and this might be a dumb question
but does anyone use VS Code instead of Visual Studio 20XX?
I have both 2019 and 2022 installed (...for some reason), but I think Code just... looks nicer? idk
Rider gang
Virtually everyone on Mac and Linux (if they're not using Rider). Some prefer it on Windows as well, but the Unity integration is a little more temperamental. I use VSCode for everything but C/C#
Is Rider another code editor?
Yeah! JetBrains generally has a great line of premium IDEs
No errors being thrown just not working this google play game authentication its setup right
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
(cos I have heard of people using 20XX for C/C# specifically, and Code for anything else)
Entirely different pieces of software - they share almost nothing. VS was implemented entirely as a native program, while VSCode's front-end is powered exclusively by web-techs. That flexibility lends well to extensibility and configurability :)
For whatever reason, I've found that VS with C/C# projects just sort of inherently works without much fiddling or configuration, but - at least when I last tried - VSCode was a pain to get working with my C projects
So, if I'm editing C# code in Code, is it only because I have 20XX that Unity can interpret it correctly or...
Oh no not at all - I believe Code has pretty good C# support through extensions nowadays, and Unity did recently revamp their VSCode support. It should work independently of whether or not you have VS installed, though you may need to install the build tools separately - I'm not entirely sure
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Ah
Ah nice - the unity extension installs the toolchain
See, I'd been learning C# through Microsoft's Learn courses, and they'd been using Code for some time
So I'd just sticked with Code
Totally valid! There for a good while Unity stopped supporting their VSCode integration and the debugger stopped working... that's likely the only reason I didn't start out on Unity with VSCode. But not a problem, nowadays
I think I'd only had VS because of some file extractions and such lol
And like once, only to learn how to build a Razor website lol
okay that's one lol too many 😅
Just fyi, call it Visual Studio or VS, not 20xx
Microsoft's become really horrible at naming things... See: their recent Game Pass changes 👀
In the context it was very clear, but if you said that later, people would likely be confused haha.
All good though
I mean, Fen is colorblind and only recently realized the logos are different colors too. They are way too similar in name AND logo
Oh wow I hadn't heard that 😅. That does make things all the worse
I guess we should also throw in VS for Mac not having any relationship with VS for Windows
My god Microsoft
I heard they were completely doing away with vs for Mac?
https://learn.microsoft.com/en-us/visualstudio/mac/what-happened-to-vs-for-mac?view=vsmac-2022
probably for the best
Sucks to be a Mac user
Why I dont have that opion vector2
Yea it sucks to be one since i cant use VS on mac and i might need it when i am going to study data science or if i get license to jetbrains (i have macbook but i use windows to make games)
whats the math behind vector2.reflect?
It seems to take two arguments - the first being the incidence vector, the second being the normal of the surface you're reflecting against
That may be something to ask in #🖱️┃input-system
Ok
how can I check if a GameObject is active?
You might need to adapt this into 2D, but https://chicio.medium.com/how-to-calculate-the-reflection-vector-7f8cab12dc42 goes over the 3D variant
If you're studying with an accredited institution, JetBrains's educational license is free :)
that's an easy google search . . .
idk i will find out since i have not started yet
Theres tons of overlaps in math like this. I mean im not doubting you may have used an underline but bolding is just weird. Not possible to really write by hand
Yh emboldening is more common in print, for obvious reasons
yea i see i can get it for free because i can apply for github student thingy with my schools name i just need to start and then i can use the mail
For stuff like this you should google it, youtube tutorials will draw it out. The dimension doesnt matter (2d or 3d) the concept is still the same. Websites like medium are generally extremely shit. Anyone can write an article and theres no way to really know if its accurate
What does this mean
Something on that line is null but you're trying to use it anyway
you have a null reference on line 16 of SceneTransition
thank you
i ended up literally just control clicking and reading the math that way
I dont really recommend doing this as it can be misleading. Remember that we have to implement operators, that operator might do more than just multiplication. For example look at quaternion * quaternion.
Plus the drawings for this stuff will be miles more useful
Vs for Mac was just resigned vs code anyway. There was never a true visual studio on mac
Im trying to make a zero g player controller (like outer wilds) with fully axis independent movement. I need camera lerping for the smooth feel. Heres what I tried, but when the player goes upside down, the controls are inverted.
Quaternion yAxis = Quaternion.AngleAxis(pitch, Vector3.right);
Quaternion xAxis = Quaternion.AngleAxis(yaw, Vector3.up);
transform.rotation = Quaternion.Slerp(transform.rotation, xAxis * yAxis, drag * Time.deltaTime);```
These are world space, you need to make them transform relative
i tried doing transform.up & .right, just bugged everything out
heres a previous solution i had that worked, but I couldn't figure out how to lerp it. csharp //transform.Rotate(Vector3.right * Mathf.DeltaAngle(pitchOld, pitch), Space.Self); //transform.Rotate(Vector3.up * Mathf.DeltaAngle(yawOld, yaw), Space.Self);
maybe the player.transform as that is what you want to be relative to
the transform in that script is the player
camera controls & playermovement are in the same script for me
and i tried using mathf.lerp on pitch & yaw, but instead of lerping the rotations it essentially just slows the camera down
so this
transform.rotation = Quaternion.Slerp(transform.rotation, xAxis * yAxis, drag * Time.deltaTime);
changes the rotation of the player not the camera?
yeah, zero g movement where the player moves
thats what i want
sense theres no camera clamping
then why are you talking about camera lerping whilst not showing camera code
yeah i guess its not camera code technically, but its separate from the movement so i don't know what else to call it
its the code im using for the players view
do you have any ideas
a way to lerp this would work too
hey guys, can anyone tell me whats going on here exactly? the last time seen float should update every frame while the target is in view, but as you can see here it is continuously set to zero. I have checked EVERY single script and none of them are doing this, and debug.logged every single time lasttimeseen is set, yet at no point is any script setting it to zero. does anyone know what might be going on? I even added the code on the right to tell me if the float its being set to is ever zero, but I'm not seeing anything in the console. Any help with this is massively appreciated.
I also set the targets[] array to be SerializeField to make sure absolutely NO other scripts are altering this value
as a matter of fact, no matter what I do setting this float value to ANYTHING, such as adding time.deltatime to it doesn't even work
and for some reason no matter what I do the same thing happens with the ID integer
Maybe you're constantly assigning it a new active target that has zero for the last time seen
see last time seen is always being set to Time.time, I also added a debug.log to whenever a target is updated, deleted, or added and its all working correctly
so I'm completely baffled
I'm not referring to assigning to last time seen
I'm referring to assigning a new active target to that element in the array
structs are passed by value, chances are you're updating the lastTimeSeen of one that's no longer being referenced anywhere. Try changing it out for a class and see if you get the same problem. If you still do, then we'll need to see more context, !code to share the full script
📃 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.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
sorry I don't quite follow, do you mean when the activeTarget is being created?
I'm also setting lastTimeSeen to Time.time here
(and the lastTimeSeen being passed in is also Time.time)
I just did it multiple times because I was starting to lose it
Did you try changing your struct to a class?
oh my goodness I'm so sorry
I have a feeling you're changing the lastTimeSeen on a copy of the activeTarget, not the original
when predicting the targets movement I forgot to return the lastTimeSeen to the returnTarget
dang that was all for nothing
sorry about that 😬 I just realised it while reading the code again
Ah that's fine, value types can sometimes be like stepping on landmines
yeah my fault I forgot that the target has to be rebuilt completely when updating its predicted movement
Inside the movedTarget function, you're potentially returning a new active target
I'm assuming this new active target would have a time of zero and if it ran every frame, the last time seen value would always be zero
I have made a sphere primitive in blender (242 verts, 480 tris) which has less tris and verts than the native Unity 3D sphere (515 verts 768 tris).
When it comes to high velocity collisions, should I opt into using a mesh collider with my custom sphere primitive as the mesh or use a sphere collider?
What is better for performance? Are there hidden downsides/overhead to using the mesh collider?
Based off my last problem where i had to use if one thing, else another thing on an OnTriggerEnter(), would I be able to do smth like OnTriggerEnter(Collider collider, other)? Or something like that
A primitive collider is always better than a mesh collider.
The sphere collider isn't "A mesh collider except that mesh is a sphere" it's a completely different thing
Can you explain why? On face value I assume that my sphere primitive is objectively better.
Because you can't get more efficient than "center and radius" which is what it uses to compute collisions
it's not a mesh, it's math
Okay that's perfect thanks 👍
Can I use 2 Colliders on an OnTriggerEnter
All collisions are between two colliders
The one that's running it, and the one it hit
No, I mean can I use OnTriggerEnter(Collider collider, other)?
The signature of your Unity Messages like OnTriggerEnter() has to match one of the signatures provided by Unity. So in this case, no
Do you see that signature on the page?
https://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html
No, its a project my friend has, he has smth like that where you have collider and other
OnTriggerEnter takes a collider that this object has hit
All collisions occur between exactly two colliders. This one and the other one
There's no such thing as colliding with two other objects. That's two different collisions
Without seeing the code we can only speculate. If it's true that he has some method taking in multiple arguments, then I would guess it's a custom method, and not the one which is a part of the Unity API
private void OnTriggerEnter(Collider collider, other)
if(other.transform.CompareTag = (bannedlol))
(Ignore the bannedlol)
That's very invalid syntax
Here, gimme a sec and Ill give you the exact code
hi, i found a random tutorial on youtube to make something look at the mouse. in that tutorial he sets the mouse position as this. What is screen to world point and why does he use it? I read the unity manual but i didnt understand it 😔
private void OnTriggerEnter(Collider collider, other)
{
if(other.transform.CompareTag = (kickstick))
{
StartCoroutine(TestPressCheck());
}
if (!base.enabled || !(touchTime + debounceTime < Time.time))
{
return;
}
touchTime = Time.time;
Debug.Log("collision detected" + collider, collider);
That would still throw a multiple compiler errors - it's not valid
That's still very invalid syntax
Just tell me how I can get Collider collider and other on OnTriggerEnter
What do you expect other to even be??
So, a position on your screen doesn't necessarily mean the same place in the world. Imagine your mouse is dead center on your screen, and you're pointing at a sign. If you spin the camera, the mouse is still dead center, but now your mouse is over a door. The screen position hasn't changed, but the world position that spot corresponds to has. This function takes a camera and checks a screen position on it, and gets back the world point that is actually over.
I've done this before but, only with Collider other
Again, you cannot
Not sure where you've copied that from but it's invalid
The thing you want to happen is fundamentally impossible and the code you've provided would not compile
You can call the parameter whatever you want - collider, other, bob, susan. But there's only one argument
Then, how do I fix it
A collision occurs between two and only two objects. This object, and the other one.
What is the "it" you want to fix
You've never described a problem?
You've never specified a problem
forgot to mention it was 2d im stupid
I need an other and a collider Collider, is there a substitute for that?
That still works, just replace my example of "turning around" with "panning the camera"
The signature for On Trigger Enter only takes one parameter https://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html
oh ok
What does this mean
We don't know what you want other to be
thank you :D
Other is a collider with a tag called bannedlol
And what is its relationship to the collision
is it the object you've collided with
How is it distinct from collider?
or just some freaky collider that likes to sit in the corner and watch
It gives me errors with collider
What errors
When a collider with the tag "bannedlol" collides with the player, they get banned
Other is that collider
So, check the collider you get in the parameter
Why do you need a second parameter?
Idk lemme try smth
You need to use only one or the other. You've meshed two completely different sets of code together and are simply trying to wing it without thinking or understanding the code. Just use either collider or other. They are simply alias' for how you'd refer to the collider that triggered the event.
void OnTriggerEnter(Collider crunchwrapSupreme) {
if (crunchwrapSupreme.gameObject.CompareTag("bannedlol")) {
// ...
There's one argument which is a Collider, and you change it's identifier to whatever you want. collider and other are just popular names and conventions - but the name itself does not matter, so long as you use it throughout the method body
How to properly attach the weapon to the sprite? i made it the child of the sprite. Placed it on top of hand. but when i play in editor, weapon's position is changed. Im not using rigging and i dont want because i really dont know how, used the animation rigging package and 2d animation package but nothings working.
In the body of the code, they've likely Frankensteined random bits from the internet that addresses the object triggering the event as collider or other but did not understand that the name doesn't matter - it's referring to the same object.
More likely this "friend" they copied the code from was ChatGPT
So I am making a top down 3D game and I have powerups that I want to be transparent. the issue is that I want the transparency to only be for specific game objects. for example When a enemy goes through the powerup I want to see the enemy through it but I dont want to see my background through the powerup as it just looks weird. is there a easy way to fix this issue?
You're using CompareTag() incorrectly. See the docs
I need CompareTag
No its if(collider.transform.CompareTag)
if other.tag == "example tag"
No
That's still wrong
Why are you trying to assign a value to a method
On the very first line after the function header, place this line (dirty port):cs var other = collider;You'll be able to use other throughout this function now. Remove , other from the function header.
You dont understand
No we understand just fine
you don't
Your code is wrong for many reasons
That has absolutely nothing to do with the fact your variable is not named "other"
No Ik what im doing, ive done this before it just wont let me do it this time
Here's the example from the docs:
if (other.gameObject.CompareTag("Player")) {
What does yours look like?
You really don't
This has never worked
Fine, ill try
it's not that it won't let you "this time" it's that the code you wrote is wrong
It was wrong
it will always be wrong
So look at the documentation
and use the function correctly
@drowsy oriole Use a thread so you don't flood this channel
Oke
I need help with collider enters
hey guys. I'm trying to implement a particle system. unfortunately when this method is called (PlayBloodEffect()) it correctly sets the position to the position of the player but it doesnt play the effect, as the Debug.Log(bloodEffect.isPlaying) returns false. how do I play my particle system?
code: https://gdl.space/litikajoma.cs
hello guys, i want to learn to make games in unity so im starting with learning c#, but i don't know where to start. so how should i? like a youtube tutorial or something?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Is bloodSplash on an active object in the scene?
is there something akin to a list that allows you to store things under strings rather than integers? i tried googling this like 40 times but couldn't find a way to word it
Dictionary
You can key them by any type, not just strings
It's a lookup table, give it a key, get the specified value
ahhhh thank you
yes
will look into this
Including any parent objects? If a parent of a particle system is disabled, it would also not play
Someone in another server just told me that it has to be an instance reference not a prefab reference. I was referencing a prefab
Ah, so then it wasn't an active object in the scene
well it is in the scene, I dragged it over
but the reference is to the prefab
not to the instance thats in the scene
Remember, a Prefab is just an object that lives in the file system instead of a scene. When you put one in the scene, that one is no longer a prefab, it's an instance of the prefab
I have a top down game and I made a object transparent but I only want the transparency to be for another specific gameobject is that possible to do easily? Like have it for example when a enemy goes through a powerup it will show the enemy through it but not the lines of my ground
Im trying to find something, but that just doesn't help. I don't really want a course, like a spreadsheet or a video maybe? Because all i find is courses.
does anyone know what IEnumerator does in a script?
im trying to understand every part of this code idk what an IEnumertor does
its a coroutine. It allows you to execute code after a delay
search for "coroutines in Unity" and you'll find plenty of stuff.
it can be very useful.
!docs
okay ty
am i correct in understanding Time.deltaTime = 1/framerate?
yes............?
iirc it's the time elapsed between the current frame and the previous frame
Running a Debug.Log(Time.deltaTime) in a void Update function should show you its output in real time
In a stable, smooth framerate, that would be 1/framerate
thats what i thought but for some reason i forgot basic c#
I want to try my hand at a really terrible high-level analogy. Bear with me 🐻
IEnumerators are like a little machine with a button and a slot. Each time you push the button, it does some work and spits something out of the slot, then goes dormant until the button is pressed once more. It repeats this until if and when it runs out of things to spit out.
The code in our methods which return an IEnumerator runs up until the point that it encounters a yield return foobar;, at which point it spits out foobar and goes dormant. The next time that the button is pressed it picks up from the next line, and again runs until the next yield return or the end of the method.
When we pass an IEnumerator to StartCoroutine(), we're handing Unity our machine so it can push the button and consume whatever it spits out. And Unity expects our machine to spit out special "yield instructions," through which we tell Unity when we would like the button to next be pressed.
yield return null will tell Unity to execute our IEnumerator again from where it left off in one frame, and the others like yield return new WaitForSeconds(2); are more self-explanatory.
This sort of logic sequence which depends on successive parts running after specific delays can totally be written in other ways, but using IEnumerators as Unity Coroutines is often a much more convenient and succinct way to accomplish it.
In an unstable non-smooth framerate it is also 1/framerate
Figures
It's more that, iirc, one value isn't tethered to the other
Like, deltaTime doesn't look at the Framerate for calculation
And similarly Framerate isn't calculated via deltaTime
Feel free to correct me tho...
I think both "look" at a common value, which is the time taken since the last frame
Hi! I just had a question about good practice when it comes to using the more expensive side of operations. I know that calling GetComponent can be bad when located in a method that is called frequently, such as the update method. However, I was wondering how frequently is bad for GetComponent? For example, I have an attack that spawns 5 projectiles and I need to access a script component on each projectile when it is spawned, would this be an acceptable rate?
Yes, that is totally fine.
Best to just instantiate the component you want directly though
public Projectile prefab
Projectile new = Instantiate(pPrefab);
Got it! Thank you! ^^
My transition for character is going well but i changed noting did everything same but my weapon is not transitioning state. I used debug log in script so issue there. Issue is in transitioning.
i have even made it from scratch but still its not wprking
I have no clue what any of this means
Simply put, my weapon is not transitioning from idle state to attack state. Even though I've done everything right.
If you did everything right, it would be working. So something was clearly done wrong.
With the 0 details you have provided that is all I can say.
Best to provide the code so we can see and help.
I have used the same values for transitioning of character's state and that works @summer stump
Ok, and the code?
this is the function im using and calling it in Update
Ok, and no nullReferenceException?
And you are sure the characterAnimator is the correct one?
YES!!! Nothing I fixed all the errors. I even tried debug log and it was working perfectly.
yes
when is OnAttack being called
oh in update
mbn
check to make sure the if statement is being executed, do a print inside of it
i'm not sure why it wouldn't be, but always good to check
I did check and it is.
and the triggers are same for both character and weapon. Character is moving but weapon is not. I also tried to do it separately, with different trigger names but nothing works
btw, i am also using different animator controllers. I tried to add layer but it was duplicating the weapon. so i just made anoter animator controller for it
as in, there are two Animator components?
yeah. one for weapon and one for character
only one is being touched here though
i have made the trigger names same
that doesn't matter, they're separate animators
Each animator has its own trigger.
The trigger name is irrelevant
That is why I asked if it is the right animator
If characterAnimator is not the one on the weapon, then of course it will not wkrk
exactly
make sure you're calling SetTrigger on both animators
weaponAnimator.SetTrigger("attack");
characterAnimator.SetTrigger("attack");
you'll have to get a reference for both animators
probably easiest to just make them public fields and assign them in the inspector
but do it however you want
this didnt work
what's your code
lemme try this
also didnt work
i also tried to do it in separate functions but that also didnt help
just in case you guys know, im not using avatar mask
all of the variables are defined properly?
YUP
try going in and manually setting the trigger and see if that works
sorry wdym by manually?
like play your game, click on the sprite, go to the animator panel, and manually enable the trigger
ohhh okay okay!!
still not working
then something's wrong with how the animator's set up, the code's fine
idk much abt animation
exactly. i even started from scratch but still its not working lol.
is it possible to use a dictionary to enable/disable something? i have a dictionary of spriterenderers and have no idea how to actually use them
Are you planing to disable a specific element or all of them?
and can you show us the code snippet where your dictionary is declared?
so i guess you want to enable one selected element and disable all others, something like that? 😄
And i guess your dictionary is Dictionary<"key", "element to disable">?
Use the key to get the value (which I assume is the renderer) like this myDict[myKey]
Then disable it
myDict[myKey].enabled = false
Basically the same as an array
speaking of dictionaries, what's the data structure that the Dictionary class implements? i don't why c# doesn't name its collections based on the data structure that it implements (i.e. a list not being called arraylist).
i'm assuming it's a hashmap but
idk maybe it's some weird form of map that i've never heard of
ahhhh this works perfectly
thanks
It's an associative array
And because the data structure isn't the most relevant information for the user
HashMap is just a Java class name BTW
ik, the data structure is called a hash table iirc
been a second since i took data structures
Basically there are many names for what that thing is called
Dictionary is one of them
i don't hear dictionary much tho
i've heard unordered assosciative array, but that's too verbose for me
Well you'll hear it a lot in C#
i think i've only ever heard it (outside of c# ofc), in Roblox, where their data structure, "tables", have a hashtable and an array implementation at the same time. pretty cool stuff
but they call the hashtable implementation a dictionary
is there a way to serialize a dictionary? or is there a better alternative of some sort?
Google unity serialized dictionary
Otherwise just serialize a list of key/value pair structs and populate the dictionary at runtime
Which btw is exactly what the serializable dictionary does.
thanks i'll read into this
funny, I've never heard of that term before, I've been reading through Skeet's book though, so maybe it'll appear there?
ah. That's why, I've mostly been hearing TMap/Map/HashMap/Table/Dictionary.
Associative Array is literally just another term on a pool of terms for the same thing.
They were talking about Dictionary when they said that
But yeah Associative array is a good term to know
It's... just one of a million
Computer Science has a way to make one thing mean 20 million things because it seems like no one's quite sure what to call an idea.
If only IEEE could actually standardize computer science fully.
I can think of zero use cases for "Associative Array" when most people are taught Map/HashMap/Dictionary
If I were to even walk up to my lecturer with that, they would raise a brow at that term
Because it is the most verbose descriptor for something that doesn't need a verbose descriptor.
I dont really find this true. Dictionary for example is really an extremely common word in computer science, used in many languages. Sure some languages might write it differently but that's really one quick google search. The overall concept of it is the same though and generally understood in those who have some experience.
And multiple things all meaning one thing is something that just exists.. everywhere. Even in our english language
I would hate to envision a world where someone writing the C# standards wrote "AssociativeArray" instead of "Dictionary" as the generic type
It would be the same as function and method - they are not called voids! You'd simply understand that they are the same (even the ill use of the word "void"), yet called different things. This isn't really a computer science specific issue though and there aren't twenty million different names for any one thing, tbf - a bit exaggerated.
They could possibly refer to the pattern as a map and you'd just have to accept that hopefully with some description, you'll be able to associate the name with the behavior/pattern/structure.
I could see the statement "one thing means 20 million things" true is if you come from a pure software eng background instead of hands on computer science. From everyone ive asked in my area, most uni's teaching SE here focus on the theory aka drawing circles and squares and acting like you planned a whole architecture. I did CS degree but Ive done a lot of SE courses. There really are a lot of confusing terms because all of them mean nothing (yes i hate SE). In CS here though, you learn terms that actually having meaning because well you're applying them in practice and actually coding something.
Software Eng. & Games Programming backgrounds
Computer Science is the more mathematics/concept based side
SEng & GProg focus on the practical
I do get the terms and stuff though.
I've had to go into Comp Sci a lot independently
just... I'd say you'd be better off using CS terms in #archived-code-general or #archived-code-advanced?
cause code-beginner would probably be someone who hasn't even gone into that realm really
https://docs.unity3d.com/ScriptReference/Animator.SetLayerWeight.html
from a quick google search
THx
I've already looked at that
How do i get the index of the layer
I have this
mask = LayerMask.NameToLayer("UpperLayer");
But it returns -1
did you look at the docs at all for Animator? I mean im not trying to be rude but i copy pasted exactly what you wrote on google and found the exact links https://docs.unity3d.com/ScriptReference/Animator.GetLayerIndex.html
because this is a layermask, nothing to do with the animator
Ok
thats not really a reason to use non-cs terms, whatever that even means. Im truly not even sure what terms you're talking about. And this isnt "ive never seen a computer before" beginner. This is game dev beginner. If people don't have any background in cs, they often are told to go through c# basics or the learn site. Using different terms to try not confusing someone will just confuse them further when they cant find what you're talking about on google.
Is there a way to count how many of a specific ScriptableObject I have, for example Weapon?
So I can randomly spawn one? Or should I put them in a List or something?
Should be able to via Resources.FindObjectsOfTypeAll
https://discussions.unity.com/t/getting-all-assets-of-the-specified-type/75031
I would recommend storing them in a list though, since it will make it easier to configure stuff such as game modes, opponents etc.
but that's not something I wanna use often right?
well should be fine I guess
🤷♂️ depends what you wanna use it for. I dont really see what functionality you could have where you need to find these at runtime
I'll have one "Weapon" prefab, then several Weapon ScriptableObjects, could add new ones or remove some at times
During combat a monster will drop a weapon, which is then randomly chosen from the list of Weapon SO's and the data is put in the prefab
yea this is something id do at editor time by storing them somewhere. Also this allows you to customize what weapons can drop if thats a feature you need
so just store them in a list? yeah kinda makes sense
Games usually make different loot pool for different enemies, which also goes in a favor of making lists manually.
Like i create a loot table SO, which holds a reference to what can drop. My enemies can take in this loot table asset. Requires more editor setup if the overall goal is just "anything can drop anything" though.
what does your loot table look like? sounds interesting
I think I'll just keep it simple with a list for now though
a list of weightings and the item that can drop. A float and the item, nothing complicated
thx 🙂
things can seem so complicated when trying to figure it out yourself and then I come here and it turns out to be so simple lol
if (item != null)
{
var itemDrop = Instantiate(monsterDropPrefab);
Item itemDropItem = itemDrop.AddComponent<Item>();
itemDropItem = item;
}```
Does this make sense?
from an outside perspective, no not really. Looks like a lot of code was cut out, or you've confused yourself. Its kinda odd you have to instantiate an item prefab but it seemingly has no item component already. Also you add the component Item, store it in itemDropItem then immediately overwrite it with item
it's because Item can be Weapon, Armor, Scroll, ... (inherited classes)
that doesnt really change anything, your code is still only adding an Item component
I changed it to this, at least it works 🙂
var itemDrop = Instantiate(monsterDropPrefab);
Weapon itemDropItem = itemDrop.AddComponent<Weapon>();
itemDropItem.WeaponSO = LootTableWeapons[itemNumber];```
!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.
https://paste.ofcode.org/BTjyZaBDhRQBaNBQuy98Hw after i made this my player started moving by itself and it got faster every second, same with my camera not sure why
Toying around with rigidbody movement. Since I'm working with physics, I know that FixedUpdate becomes much more important. However, gathering inputs seem like they should still be done during simple update. As a result, I have a basic jumping script to show to see if you guys see any glaring flaws with my idea.
https://pastebin.com/Cv1517ZZ
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Side note, this only does jumping in game, so that PlayerMovementInput being unused is something I'm already aware of
This is how it should be done.
Nice!
here is a video
could i use a script as a componen
A script is not a Component.
is the green block intersecting with your player?
but you can apply it to an object like one
Only when it has a class derived from Component
and my script does have a class
I don’t think so this is it
I cnat right click so it’s hard to move around sorry
why do you have two cameras inside eachother
ok
so what is your suggestion
On?
check all your colliders
getting a suitable component
What are you referring to? Perhaps, you could formulate a more specific question?
i need to save a sring to a comonent so i can DDoL the component and keep it between scenes
Create a generic Singleton class, derive your Component from it and unparent its GameObject
You could've even done gameObject without this this whole time
well
i could have
but wheres the fun in that
although
do i have to put the DDoL in Awake()
Yes, it has to be put in Awake. Copy-paste the whole Singleton class from google
Hi,
I develop my system of inventory so I create a list of all weapons and all charms I will have. But, Unity send me this warning :
You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all
Item is a ScriptableObject.
The code :
public List<Item> Weapons = new();
public List<Item> Charm = new();
Even if Item was a MonoBehaviour, a List of MonoBehaviours is not a MonoBehaviour itself
Make sure the warning isn't an old one and show the entire warning
Why does my sprinting/run code not work?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public CharacterController2D controller;
public Animator animator;
public float walkSpeed = 40f;
public float runSpeed = 100f;
float horizontalMove = 0f;
private bool jump = false;
private bool crouch = false;
private bool run = false;
void Update () {
// Jump logic
if (Input.GetButtonDown("Jump"))
{
jump = true;
animator.SetBool("IsJumping", true);
}
// Sprint logic
if (Input.GetButtonDown("Run"))
{
//walkSpeed = runSpeed;
run = true;
}
else if (Input.GetButtonUp("Run"))
{
//walkSpeed = oWalkSpeed;
run = false;
}
// Crouch logic
if (Input.GetButtonDown("Crouch"))
{
crouch = true;
} else if (Input.GetButtonUp("Crouch"))
{
crouch = false;
}
// Movement calculation
if (!run)
{
horizontalMove = Input.GetAxis("Horizontal") * walkSpeed;
} else
{
horizontalMove = Input.GetAxis("Horizontal") * runSpeed;
}
animator.SetFloat("Speed", Mathf.Abs(horizontalMove));
}
public void OnLanding ()
{
animator.SetBool("IsJumping", false);
}
public void OnCrouching (bool isCrouching)
{
animator.SetBool("IsCrouching", isCrouching);
}
void FixedUpdate ()
{
// Move our character
controller.Move(horizontalMove * Time.fixedDeltaTime, crouch, jump);
jump = false;
}
} ```
What is not working ?
And I think you need to add Time.fixedDeltaTime at the end of horizontalMove like this :
horizontalMove = Input.GetAxis("Horizontal") * walkSpeed * Time.fixedDeltaTime;
And why you use a bool to know if you run or not ?
You can use the condition of the keypressed directly for Movement calculation
Good point
The player isn't speeding up when pressing the sprint/run button
Are you assigned what is the Button "Run" ?
hey for some reason unity thinks this is a scenemanagement.scene, anybody know why
Maybe show all of it?
public GameObject Human, Box, Spike;
public void HumanButton()
{
Human = Instantiate(Human, ItemSpawner.transform.position);
}``` CS1503 Argument 2: cannot convert from 'UnityEngine.Vector3' to 'UnityEngine.SceneManagement.Scene'
there you go
Where is your rotation argument? https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
The method takes three arguments. If you're wanting to use a position as well, it's not optional to leave out rotation.
do you also have a method named Instantiate? That error looks suspicious still
Use Quaternion.identity
i did
There is no Instantiate method that takes in a scene. The error happends because you have a method that does take in a scene
So how did you solve it?
The only reason why it would give that error is if it knows a signature that takes scene as the first parameter. The docs are clear this isn't possible, so it was your own method
That, or a library
!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.
quaternion.ientify
Yes, you were also missing a parameter, but you still have a dangling method that clearly should not exist
Hello, as someone here suggested: i used _rb.velocity = _movementKeys.y * transform.forward + _movementKeys.x * transform.right + _rb.velocity.y * Vector3.up; for moving locally the player. While this works, it has a flow: When i press "S" the player gets launched in the air, until i stop pressing "S" (it doesn't go backwards, it only flies). Any solution for this? Here's the code: https://paste.ofcode.org/34hYuEMRDbyMi6mRpFXk7JW
if i have a coroutine that goes something like this
IEnumerator CoroutineName()
{
yield return new WaitForSeconds(amount);
FunctionName();
}
and i call the coroutine while it's waiting to call FunctionName, it will restart the coroutine back from scratch right?
well it worked
Right well you clearly have no interest in actually fixing it so nevermind
- _rb.velocity.y * Vector3.up
why is that if youre already adding to the Y value using the movement keys
the y value is the z value
Guys, just to make sure, C# didnt evolve over last 3 years? Im watching a tutorial and i don't want to know that something doesn't work anymore.
'Cause of the new input system and stuff, i use Vector2 to take any movement key
is there a way to make it start again from scratch?
im trying to create a system where if an enemy goes unharmed for X seconds, it starts to heal
is the game that youre making 3d or 2d
3D, but it uses the new input system that stores the input in a Vector2
why are you trying to move up then?
StartCoroutine returns a value, store it in a variable. When you need to restart the coroutine, first run StopCoroutine(c) and pass the variable in, so the previous coroutine stops running.
shouldn't transform.forward modify my z value?
transform.forward moves you on your Z axis, transform.right moves you on your X axis, Vector3.up is (0, 1, 0) which should move you upwards
right
so, what should i put for the y?
I cannot just put a float there
The C# version Unity uses hasn't changed in at least 5 years, so you're good if you look for Unity-specific tutorials.
Microsoft still updates C# once a year with new features though, so there will be things that don't exist if your source is the official MS documentation
do you want the player to move up as if there was no gravity or do you want them to have a normal jump
Normal
It shouldn't jump at all, but i still need some gravity
so that's why i'm keeping the y velocity
If im currently learning on .net engine in visual studio and later switch to unity will i have issues?
Most likely yes, do you know which .NET version you're using? Latest is .NET 8
rigidbody already has a gravity
yes, but shouldn't velocity overwrite it?
if i put zero there, there should be no gravity
the only "issues" you would face would be errors if you try to use a c# feature from a version newer than c# 9 or types from the latest .net versions. your IDE will tell you that these are errors though so you can correct them
it should, but why do you want to override it?
do you want custom gravity?
ehh, im using .NET 8 but due to tutorial using the .NET 5 template i had to copy and paste the .NET 5 template
i dont want to overwrite the y velocity, i just want to overwrite the x and z velocity for moving the player
then why are you multiplying the rb velocity by vector3.up?
