I have the Code below and I’m trying to round the PerlinNoise(x,z) so I’ve put it equal to Yscale and tried to round it. the issue is that I get the error «The name `Math’ does not exist in the current context» for that Line. Any Ideas?
using UnityEngine;
using System.Collections;
public class voxelcreate : MonoBehaviour {
private int origin = 0;
private Vector3 ChunkSize = new Vector3 (32,6,32);
private float Height = 10.0f;
private float NoiseSize = 10.0f;
private float Yscale=0;
private GameObject root;
public float PerlinNoise(float x, float y)
{
float noise = Mathf.PerlinNoise( x / NoiseSize, y / NoiseSize );
return noise * Height;
}
// Use this for initialization
void Start () {
for(int x = 0; x < 33; x++){
bool isMultiple = x % ChunkSize.x == 0;
if(isMultiple == true){
origin = x;
Chunk();}
}
}
// Update is called once per frame
void Chunk (){
int ranNumber = Random.Range(8, 80);
int ranNumber2 = Random.Range(8, 20);
Height = ranNumber2;
NoiseSize = ranNumber;
for(int x = 0; x < ChunkSize.x; x++)
{
for(int y = 0; y < ChunkSize.y; y++)
{
for(int z = 0; z < ChunkSize.z; z++)
{
GameObject box = GameObject.CreatePrimitive(PrimitiveType.Cube);
int Yscale = (int)Math.Round((PerlinNoise( x, z)), 0);
box.transform.position = new Vector3( origin+x , y+Yscale, z);
}}}}}
Steven
164k23 gold badges323 silver badges429 bronze badges
asked Nov 1, 2013 at 22:44
1
Add
using System;
at the top of the file.
Or use System.Math
instead of Math
.
answered Nov 1, 2013 at 22:46
GuffaGuffa
679k108 gold badges728 silver badges999 bronze badges
3
It is true you could add using System
. However, Unity has Mathf
Why would you rather use the built in Mathf?
System.Math
uses doubles. UnityEngine.Mathf
uses floats. Since most of Unity uses floats, it is better to use Mathf
so that you don’t have to constantly convert floats and doubles back and forth.
answered Nov 14, 2013 at 9:18
4
In ASP.NET Core, you need to get the System.Runtime.Extension package first, maybe via NuGet Package Manager in Visual Studio or by command line.
Details about the package can be found here.
Finally you need to give:
using System
And then you can use methods of this class:
using System;
namespace Demo.Helpers
{
public class MathDemo
{
public int GetAbsoluteValue()
{
var negativeValue = -123;
return Math.Abs(negativeValue);
}
}
}
answered Jan 2, 2017 at 10:43
BlazeBlaze
1,5922 gold badges21 silver badges20 bronze badges
Permalink
Cannot retrieve contributors at this time
description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
---|---|---|---|---|---|
Compiler Error CS0103 |
Compiler Error CS0103 |
07/20/2015 |
CS0103 |
CS0103 |
fd1f2104-a945-4dba-8137-8ef869826062 |
Compiler Error CS0103
The name ‘identifier’ does not exist in the current context
An attempt was made to use a name that does not exist in the class, namespace, or scope. Check the spelling of the name and check your using directives and assembly references to make sure that the name that you are trying to use is available.
This error frequently occurs if you declare a variable in a loop or a try
or if
block and then attempt to access it from an enclosing code block or a separate code block, as shown in the following example:
[!NOTE]
This error may also be presented when missing thegreater than
symbol in the operator=>
in an expression lambda. For more information, see expression lambdas.
using System; class MyClass1 { public static void Main() { try { // The following declaration is only available inside the try block. var conn = new MyClass1(); } catch (Exception e) { // The following expression causes error CS0103, because variable // conn only exists in the try block. if (conn != null) Console.WriteLine("{0}", e); } } }
The following example resolves the error:
using System; class MyClass2 { public static void Main() { // To resolve the error in the example, the first step is to // move the declaration of conn out of the try block. The following // declaration is available throughout the Main method. MyClass2 conn = null; try { // Inside the try block, use the conn variable that you declared // previously. conn = new MyClass2(); } catch (Exception e) { // The following expression no longer causes an error, because // the declaration of conn is in scope. if (conn != null) Console.WriteLine("{0}", e); } } }
C# Compiler Error
CS0103 – The name ‘identifier’ does not exist in the current context
Reason for the Error
You will usually receive this error when you are trying to use a identifier name in C# that doesnot exist with-in the current scope. One of the simple example of this error is when you declare a variable with-in a try block and try to access it in the catch block.
In the below example, the variable i is declared inside the try block, so its scope is restricted to the try block. When you try accessing it in the catch block is when you will receive the error.
using System; public class DeveloperPublish { public static void Main() { try { int i = 1; int j = 0; int result = i / j; } catch(DivideByZeroException) { string message = i + " is divivided by zero"; Console.WriteLine(message); } } }
Error CS0103 The name ‘i’ does not exist in the current context ConsoleApp1 C:UsersSenthilsourcereposConsoleApp1ConsoleApp1Program.cs 16 Active
Solution
To fix the error move the declaration of the identifier that is causing the error to a higher scope so that it is available when it is accessed.
For example, to fix the error in the above code snippet, we just need to move the declaration of the identifier outside of the try block.
using System; public class DeveloperPublish { public static void Main() { int i = 1; try { int j = 0; int result = i / j; } catch(DivideByZeroException) { string message = i + " is divivided by zero"; Console.WriteLine(message); } } }
0 / 0 / 0
Регистрация: 03.03.2019
Сообщений: 7
1
03.03.2019, 22:27. Показов 13926. Ответов 11
Всем привет, перечитал много тем по поводу данной ошибки, но у меня немного другая ситуация, код компилируется нормально, без ошибок, но при запуске сервера выдает уже ошибки
Например у меня есть класс где функции транспорта, когда при запуске сервера я вызываю загрузку транспорта — выходит ошибка
Код
CS0103: The name 'VehicleF' does not exist in the current context -> Class1.cs:16
Файл запуска сервера
C# | ||
|
Файл с функциями транспорта
C# | ||
|
А так же где у меня идет работа с базой данных выходит ошибка
Код
CS0012: The type 'DbConnection' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. -> connect.cs:15
Добавлено через 1 час 24 минуты
Большое спасибо вам, но я перехожу по вашим ссылкам, там такие же ответы на другие ссылки, а затем опять ответы со ссылками, где-то на 5 переходе я бросил это занятие, так как видимо ответов здесь не бывает -_-
Добавлено через 9 минут
Тем более меня не интересуют темы где люди не обьявляют переменные, меня интересует почему у меня методы из одного класса не вызываются в другом, классы по разным файлам
Добавлено через 16 минут
Если я прописываю два класса в одном файле то все хорошо, а если по разным то вот такие ошибки, может кто сказать как линкануть файл? Указать его вначале? Подключить? Я думал что если все одним проектом то таких проблем быть не должно, но видимо ошибся
__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь
0
- Remove From My Forums
-
Question
-
User397255882 posted
My asp.net page runs fine in VWD Express 2010 but on the server i get this error:
error CS0103: The name 'DropDownList_Nodes' does not exist in the current context
If anyone can help me I would appreciate it.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; namespace OrionNodeEvent { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack)//only do on 1st page load { FillListBox(); } }//end Page_Load protected void Submit_Click(object sender, EventArgs e) { string connectionString = @"data source=****;initial catalog=****;user id=*****;" + "password=****;packet size=4096;persist security info=False;connect timeout=30000; Trusted_Connection=yes"; string insertSQL; DateTime currentTime = DateTime.UtcNow; insertSQL = @"USE **** INSERT INTO ***** ("; insertSQL += "Node_Name, Event, Solution, Time) "; insertSQL += "VALUES ('"; insertSQL += DropDownList_Nodes.SelectedItem.ToString() + "', '"; insertSQL += TextBox_Event.Text + "', '"; insertSQL += TextBox_Solution.Text + "', '"; insertSQL += currentTime + "')"; SqlConnection sql_connection = new SqlConnection(connectionString); SqlCommand sql_command = new SqlCommand(insertSQL, sql_connection); int added = 0;//counter for rows inserted to DB try { sql_connection.Open(); added = sql_command.ExecuteNonQuery(); Label_Info.Text = added.ToString() + " records inserted."; } catch(Exception error) { Label_Info.Text = error.Message; } finally { sql_connection.Close(); sql_connection.Dispose(); } }//end Submit_Click protected void FillListBox() { string connectionString = @"data source=****;initial catalog=****;user id=****;" + "password=****;packet size=4096;persist security info=False;connect timeout=30000; Trusted_Connection=yes"; DropDownList_Nodes.Items.Clear(); string selectSQL = @"USE **** SELECT ***, *** FROM *** ORDER BY ***"; SqlConnection sql_connection = new SqlConnection(connectionString); SqlCommand sql_command = new SqlCommand(selectSQL, sql_connection); SqlDataReader sql_reader; try { sql_connection.Open(); sql_reader = sql_command.ExecuteReader(); while (sql_reader.Read()) { ListItem newitem = new ListItem(); newitem.Text = sql_reader["****"].ToString(); newitem.Value = sql_reader["****"].ToString(); DropDownList_Nodes.Items.Add(newitem); }//end while sql_reader.Close(); sql_reader.Dispose(); }//end try catch(Exception error) { Label_Info.Text = error.Message; } finally { sql_connection.Close(); sql_connection.Dispose(); } }//end FillListBox public override void VerifyRenderingInServerForm(Control control) { return; } }//end public partial class _Default : System.Web.UI.Page }//end namespace OrionNodeEvent
// ASP PAGE *************************************** <%@ Language="C#" AutoEventWireup="true" CodeBehind="OrionNodeEvent.aspx.cs" Inherits="OrionNodeEvent._Default" Src="OrionNodeEvent.aspx.cs" %> <html> <head> <title>Orionz</title> </head> <body> <h2>Select a Node to add an event and resolution.</h2> <p><asp:DropDownList ID="DropDownList_Nodes" runat="server"></asp:DropDownList></p> <p><strong>Event</strong><asp:TextBox ID="TextBox_Event" runat="server" style="margin-left: 25px" Width="500px" Height="150px" TextMode="MultiLine" MaxLength="8000"></asp:TextBox></p> <p><strong>Solution</strong><asp:TextBox ID="TextBox_Solution" runat="server" style="margin-left: 10px" Width="500px" Height="150px" TextMode="MultiLine" MaxLength="8000"></asp:TextBox> </p> <p><asp:Button ID="Button_Submit" runat="server" Text="Submit" OnClick="Submit_Click"/></p> <p><asp:Label ID="Label_Info" runat="server" Text="" ></asp:Label> </p> </body> </html>
Answers
-
User397255882 posted
SOLVED:
Added these control statements to the Default.aspx.cs:
protected global::System.Web.UI.HtmlControls.HtmlForm form1; protected System.Web.UI.WebControls.Label Label_Info; protected System.Web.UI.WebControls.DropDownList DropDownList_Nodes; protected System.Web.UI.WebControls.TextBox TextBox_Event; protected System.Web.UI.WebControls.TextBox TextBox_Solution; protected System.Web.UI.WebControls.Button Button_Submit;
The server was ignoring the designer file.
Now it loads!
-
Marked as answer by
Thursday, October 7, 2021 12:00 AM
-
Marked as answer by
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
public static class MeshGenerator
{
public static MeshData GenerateTerrainMesh(float[,] borderedSizeMap, float borderedSizeMultiplier, AnimationCurve _borderedSizeCurve, int levelOfDetail)
{
AnimationCurve borderedSizeCurve = new AnimationCurve(_borderedSizeCurve.keys);
int borderedSize = borderedSizeMap.GetLength(0);
int meshSize = borderedSize - 2;
float topLeftX = (meshSize - 1) / -2f;
float topLeftZ = (meshSize - 1) / 2f;
int meshSimplificationIncrement = (levelOfDetail == 0) ? 1 : levelOfDetail * 2;
int verticesPerLine = (meshSize - 1) / meshSimplificationIncrement + 1;
MeshData meshData = new MeshData(verticesPerLine);
int[,] vertexIndicesMap = new int[borderedSize, borderedSize];
int meshVertexIndex = 0;
int borderVertexIndex = -1;
for (int y = 0; y < borderedSize; y += meshSimplificationIncrement)
{
for (int x = 0; x < borderedSize; x += meshSimplificationIncrement)
{
bool isBorderVertex = y == 0 || y == borderedSize - 1 || x == 0 || x == borderedSize - 1;
if (isBorderVertex)
{
vertexIndicesMap[x, y] = borderVertexIndex;
borderVertexIndex--;
}
else
{
vertexIndicesMap[x, y] = meshVertexIndex;
meshVertexIndex++;
}
}
}
for (int y = 0; y < borderedSize; y+= meshSimplificationIncrement)
{
for (int x = 0; x < borderedSize; x+= meshSimplificationIncrement)
{
int vertexIndex = vertexIndicesMap[x, y];
Vector2 percent = new Vector2((x - meshSimplificationIncrement) / (float)meshSize, (y - meshSimplificationIncrement) / (float)meshSize);
float height = heightCurve.Evaluate(heightMap[x, y]) * heightMultiplier;
Vector3 vertexPosition = new Vector3(topLeftX + percent.x * meshSize, height, topLeftZ - percent.y * meshSize);
meshData.AddVertex(vertexPosition, percent, vertexIndex);
if (x < borderedSize - 1 && y < borderedSize - 1)
{
int a = vertexIndicesMap[x, y];
int b = vertexIndicesMap[x + meshSimplificationIncrement, y];
int c = vertexIndicesMap[x, y + meshSimplificationIncrement];
int d = vertexIndicesMap[x + meshSimplificationIncrement, y + meshSimplificationIncrement];
meshData.AddTriangle(a, d, c);
meshData.AddTriangle(d, a, b);
}
vertexIndex++;
}
}
return meshData;
}
}
public class MeshData
{
Vector3[] vertices;
int[] triangles;
Vector2[] uvs;
Vector3[] borderVertices;
int[] borderTriangles;
int triangleIndex;
int borderTriangleIndex;
public MeshData(int verticesPerLine)
{
vertices = new Vector3[verticesPerLine * verticesPerLine];
uvs = new Vector2[verticesPerLine * verticesPerLine];
triangles = new int[(verticesPerLine - 1) * (verticesPerLine - 1) * 6];
borderVertices = new Vector3[verticesPerLine * 4 + 4];
borderTriangles = new int[24 * verticesPerLine];
}
public void AddVertex(Vector3 vertexPosition, Vector2 uv, int vertexIndex)
{
if (vertexIndex < 0)
{
borderVertices[-vertexIndex - 1] = vertexPosition;
}
else
{
vertices[vertexIndex] = vertexPosition;
uvs[vertexIndex] = uv;
}
}
public void AddTriangle(int a, int b, int c)
{
if (a < 0 || b < 0 || c < 0)
{
borderTriangles[borderTriangleIndex] = a;
borderTriangles[borderTriangleIndex + 1] = b;
borderTriangles[borderTriangleIndex + 2] = c;
borderTriangleIndex += 3;
}
else
{
triangles[triangleIndex] = a;
triangles[triangleIndex + 1] = b;
triangles[triangleIndex + 2] = c;
triangleIndex += 3;
}
}
Vector3[] CalculateNormals()
{
Vector3[] vertexNormals = new Vector3[vertices.Length];
int triangleCount = triangles.Length / 3;
for (int i = 0; i < triangleCount; i++)
{
int normalTriangleIndex = i * 3;
int vertexIndexA = triangles[normalTriangleIndex];
int vertexIndexB = triangles[normalTriangleIndex + 1];
int vertexIndexC = triangles[normalTriangleIndex + 2];
Vector3 triangleNormal = SurfaceNormalFromIndices(vertexIndexA, vertexIndexB, vertexIndexC);
vertexNormals[vertexIndexA] += triangleNormal;
vertexNormals[vertexIndexB] += triangleNormal;
vertexNormals[vertexIndexC] += triangleNormal;
}
int borderTriangleCount = borderTriangles.Length / 3;
for (int i = 0; i < triangleCount; i++)
{
int normalTriangleIndex = i * 3;
int vertexIndexA = borderTriangles[normalTriangleIndex];
int vertexIndexB = borderTriangles[normalTriangleIndex + 1];
int vertexIndexC = borderTriangles[normalTriangleIndex + 2];
Vector3 triangleNormal = SurfaceNormalFromIndices(vertexIndexA, vertexIndexB, vertexIndexC);
if (vertexIndexA >= 0)
{
vertexNormals[vertexIndexA] += triangleNormal;
}
if (vertexIndexB >= 0)
{
vertexNormals[vertexIndexB] += triangleNormal;
}
if (vertexIndexC >= 0)
{
vertexNormals[vertexIndexC] += triangleNormal;
}
}
for (int i = 0; i < vertexNormals.Length; i++)
{
vertexNormals[i].Normalize();
}
return vertexNormals;
}
Vector3 SurfaceNormalFromIndices(int indexA, int indexB, int indexC)
{
Vector3 pointA = (indexA < 0) ? borderVertices[-indexA - 1] : vertices[indexA];
Vector3 pointB = (indexB < 0) ? borderVertices[-indexB - 1] : vertices[indexB];
Vector3 pointC = (indexC < 0) ? borderVertices[-indexC - 1] : vertices[indexC];
Vector3 sideAB = pointB - pointA;
Vector3 sideAC = pointC - pointA;
return Vector3.Cross(sideAB, sideAC).normalized;
}
public Mesh CreateMesh()
{
Mesh mesh = new Mesh();
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.uv = uvs;
mesh.normals = CalculateNormals();
return mesh;
}
}
Скрипт не работает
Скрипт не работает
Вот такой простенький скрипт но консоль выдает данную ошибку=Assets/M2.cs(8,20): error CS0103: The name `col’ does not exist in the current context
И еще желтую ошибку=Assets/M2.cs(10,28): warning CS0219: The variable `rotationY’ is assigned but its value is never used
Используется csharp
using System.Collections;
public class Moving2 : MonoBehaviour {
void Update ()
{
if(col.gameObject.name == «RollerBall»)
{
Quaternion rotationY = Quaternion.AngleAxis (180, Vector3.up);
}
}
}
- developers
- UNец
- Сообщения: 15
- Зарегистрирован: 30 янв 2016, 22:55
Re: Скрипт не работает
Smouk 03 мар 2016, 10:36
1. Из этого не понять в чем именно ошибка. Где объявлено col и зачем? Для получения имени объекта если скрипт висит на нем это не нужно.
В принципе не очень верно каждый update без необходимости сравнивать текст. Лучше при создании объекта использовать флаг или int с типом объекта, например.
2. Если перевести там прямо написано, что переменная rotationY никогда не используется.
Последний раз редактировалось Smouk 03 мар 2016, 10:39, всего редактировалось 2 раз(а).
- Smouk
- UNIт
- Сообщения: 146
- Зарегистрирован: 16 сен 2009, 08:47
Re: Скрипт не работает
BladeBloodShot 03 мар 2016, 10:38
Ну так переведи ошибки, нет определения col то бишь надо public var col = там чему то;
- BladeBloodShot
- UNец
- Сообщения: 38
- Зарегистрирован: 03 фев 2016, 22:31
Re: Скрипт не работает
developers 03 мар 2016, 12:06
А насчет 2 причины
- developers
- UNец
- Сообщения: 15
- Зарегистрирован: 30 янв 2016, 22:55
Re: Скрипт не работает
iLLoren 03 мар 2016, 13:59
developers писал(а):А насчет 2 причины
Научись разбираться с мелочами самостоятельно, тебе самому то не стыдно что имея видео о том как с 0 сделать всё правильно ты косячишь и вместо пересмотров урока ты плачешь на форуме о проблемах которые сам можешь легко решить?
-
iLLoren - UNIт
- Сообщения: 103
- Зарегистрирован: 31 дек 2015, 12:00
Re: Скрипт не работает
Tolking 03 мар 2016, 14:16
Желтая ошибка называется предупреждением и в переводе с английского гласит: ты нахрена опредилил переменную `rotationY’ если нигде ее не используешь!
Таки да!!! Английский знать надо или пользоваться переводчиком…
Ковчег построил любитель, профессионалы построили Титаник.
-
Tolking - Адепт
- Сообщения: 2684
- Зарегистрирован: 08 июн 2009, 18:22
- Откуда: Тула
Вернуться в Скрипты
Кто сейчас на конференции
Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 6
- Remove From My Forums
-
Вопрос
-
Hello,
I have created a very simple SSIS Package with only one component.
Script task which has below code in Main method
public void Main()
{
// TODO: Add your code here
string name = «ABC»;
name = name + » XYZ»;
Dts.TaskResult = (int)ScriptResults.Success;
}When I try to debug the script task, and when I hover the mouse on the variable «name» nothing appears in a tiptop.
When I say Quick watch by selecting this variable , it display above error.
Error in Quick watch window is
error CS0103: The name ‘name’ does not exist in the current context
How can i see the values of the variables any help is appreciated.
-
Изменено
3 апреля 2016 г. 14:47
-
Изменено
Ответы
-
Hi Desh200,
I was testing in Visual studio 2015 as well.
What happens if debugging in a C# project?
If the error still persists, you can post it in the
visual studio forum. If the error only happens in a script task in an SSIS project, you can post it in theSQL Server data tools forum.
You would get more appropriate response there.
By the way, since the SSDT for Visual Studio 2015 is still a preview version, it is not recommended to use it in your development work.
Eric Zhang
TechNet Community Support-
Предложено в качестве ответа
HoroChan
19 апреля 2016 г. 9:25 -
Помечено в качестве ответа
Eric__Zhang
24 апреля 2016 г. 10:19
-
Предложено в качестве ответа