Set GameObject From Http Request Result in Unity - c#

I have 4 buttons in my project and all these buttons call different score results from server. At awake function I generate a table with random values and it works pretty fine. However when I call a function and get results I couldnt set the table with received values because entryContainer and entryTemplate would be null which I think should not be because they are instantiated!. Here is my code which works pretty fine at page opening but could not set items after receiving request
using Assets.Scripts.HttpPost;
using Assets.Scripts.Models;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
public class HighScoreTable : MonoBehaviour
{
public static Transform entryContainer;
public static Transform entryTemplate;
public List<HighscoreEntry> highscoreEntryList;
public static List<Transform> highscoreEntryTransformList;
public static bool isChanged = false;
public void Awake()
{
// Works pretty fine at opening
entryContainer = transform.Find("highscoreEmptyContainer");
entryTemplate = entryContainer.Find("highscoreEntryTemplate");
entryTemplate.gameObject.SetActive(false);
highscoreEntryList = new List<HighscoreEntry>() {
new HighscoreEntry{score = 33.6, username = "Osman"},
new HighscoreEntry{score = 46033.5, username = "Ahmet"},
new HighscoreEntry{score = 1833.5, username = "Veli"},
new HighscoreEntry{score = 563.5, username = "Can"},
new HighscoreEntry{score = 433.5, username = "Esma"},
new HighscoreEntry{score = 6533.5, username = "Gözde"},
new HighscoreEntry{score = 733.5, username = "Ayşe"},
new HighscoreEntry{score = 733.5, username = "Fatma"},
new HighscoreEntry{score = 383.5, username = "Hayriye"}
};
//generates table its ok
highscoreEntryTransformList = new List<Transform>();
foreach (var highscoreEntry in highscoreEntryList)
{
CreateHighscoreEntryTransform(highscoreEntry, entryContainer, highscoreEntryTransformList);
}
}
public void Update()
{
}
private void CreateHighscoreEntryTransform(HighscoreEntry highscoreEntry, Transform container, List<Transform> transformList)
{
float templateHeight = 30f;
while (container == null)
container = transform.Find("highscoreEmptyContainer");
Transform entryTransform = Instantiate(entryTemplate, entryContainer);
RectTransform entryRectTransform = entryTransform.GetComponent<RectTransform>();
entryRectTransform.anchoredPosition = new Vector2(0, -30 - templateHeight * transformList.Count);
entryTransform.gameObject.SetActive(true);
int rank = transformList.Count + 1;
string rankString;
switch (rank)
{
default:
rankString = rank + "TH"; break;
case 1: rankString = "1ST"; break;
case 2: rankString = "2ND"; break;
case 3: rankString = "3RD"; break;
}
entryTransform.Find("posText").GetComponent<Text>().text = rankString;
double score = highscoreEntry.score;
entryTransform.Find("scoreText").GetComponent<Text>().text = score.ToString();
entryTransform.Find("nameText").GetComponent<Text>().text = highscoreEntry.username;
transformList.Add(entryTransform);
}
#region AllVerbal
public WWW AllVerbalGet(string postAddress, string jsonData)
{
entryContainer = transform.Find("highscoreEmptyContainer");
entryTemplate = entryContainer.Find("highscoreEntryTemplate");
entryTemplate.gameObject.SetActive(false);
WWW www;
byte[] formData = null;
try
{
Hashtable postHeader = new Hashtable();
postHeader.Add("Content-Type", "application/json");
// convert json string to byte
if (!string.IsNullOrEmpty(jsonData))
{
formData = System.Text.Encoding.UTF8.GetBytes(jsonData);
}
www = new WWW(postAddress, formData, postHeader);
StartCoroutine(WaitForAllVerbalGetRequest(www));
}
catch (System.Exception ex)
{
www = null;
}
return www;
}
//Wait for the www Request
IEnumerator WaitForAllVerbalGetRequest(WWW www)
{
yield return www;
if (www.error == null)
{
//Print server response
try
{
LeaderboardListModel result = JsonUtility.FromJson<LeaderboardListModel>("{\"leaders\":" + www.text + "}");
highscoreEntryList = new List<HighscoreEntry>();
// Items received and converted to model successfully!
HighscoreEntry temp;
foreach (var item in result.leaders)
{
temp = new HighscoreEntry();
temp.username = item.username;
temp.score = item.totalScore;
temp.weekscore = item.weeklyTotalScore;
highscoreEntryList.Add(temp);
}
highscoreEntryTransformList = new List<Transform>();
foreach (var highscoreEntry in highscoreEntryList)
{
// HERE IS THE PROBLEM ENTRY CONTAINER IS NULL BUT ITS INSTANTIATED AT AWAKE FUNCTION!!!!!!!!!!!
// I ALSO TRY TO SET THESE ITEMS AGAIN BUT STILL RETURNS NULL
//entryContainer = transform.Find("highscoreEmptyContainer");
//entryTemplate = entryContainer.Find("highscoreEntryTemplate");
//entryTemplate.gameObject.SetActive(false);
//WHAT SHOULD I DO entry container is null!! :(
CreateHighscoreEntryTransform(highscoreEntry, entryContainer, highscoreEntryTransformList);
}
isChanged = true;
}
catch (System.Exception ex)
{
}
}
else
{
try
{
highscoreEntryList = new List<HighscoreEntry>();
highscoreEntryTransformList = new List<Transform>();
foreach (var highscoreEntry in highscoreEntryList)
{
CreateHighscoreEntryTransform(highscoreEntry, entryContainer, highscoreEntryTransformList);
}
}
catch (System.Exception)
{
}
}
}
#endregion
public void allVerbalButton_Click()
{
isChanged = true;
AllVerbalGet(HttpOperations.allVerbalURL, null);
}
public void allCompButton_Click()
{
isChanged = true;
AllVerbalGet(HttpOperations.allCompURL, null);
}
public void Top10VerbalButton_Click()
{
isChanged = true;
AllVerbalGet(HttpOperations.Top10VerbalURL, null);
}
public void Top10ComputButton_Click()
{
isChanged = true;
AllVerbalGet(HttpOperations.Top10CompURL, null);
}
[System.Serializable]
public class HighscoreEntry
{
public double score;
public string username;
public double weekscore;
}
}
I am pretty new at unity but couldnt solve it :( Any help would be great

Related

error CS0234: The type or namespace name 'OpenURL' does not exist in the namespace 'Application'

Hi' i am using Unity Engine to build a VR game and i'm kinda stuck here, what should i do next? (it says smtng about line-144. If any of you could help me with this it would be very appritiated:)
i dont know what to write anymor cuz of that:
It looks like your post is mostly code; please add some more details.
code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System;
using System.IO;
using System.Reflection;
[CustomEditor(typeof(Readme))]
[InitializeOnLoad]
public class ReadmeEditor : Editor
{
static string s_ShowedReadmeSessionStateName = "ReadmeEditor.showedReadme";
static string s_ReadmeSourceDirectory = "Assets/TutorialInfo";
const float k_Space = 16f;
static ReadmeEditor()
{
EditorApplication.delayCall += SelectReadmeAutomatically;
}
static void RemoveTutorial()
{
if (EditorUtility.DisplayDialog("Remove Readme Assets",
$"All contents under {s_ReadmeSourceDirectory} will be removed, are you sure you want to proceed?",
"Proceed",
"Cancel"))
{
if (Directory.Exists(s_ReadmeSourceDirectory))
{
FileUtil.DeleteFileOrDirectory(s_ReadmeSourceDirectory);
FileUtil.DeleteFileOrDirectory(s_ReadmeSourceDirectory + ".meta");
}
else
{
Debug.Log($"Could not find the Readme folder at {s_ReadmeSourceDirectory}");
}
var readmeAsset = SelectReadme();
if (readmeAsset != null)
{
var path = AssetDatabase.GetAssetPath(readmeAsset);
FileUtil.DeleteFileOrDirectory(path + ".meta");
FileUtil.DeleteFileOrDirectory(path);
}
AssetDatabase.Refresh();
}
}
static void SelectReadmeAutomatically()
{
if (!SessionState.GetBool(s_ShowedReadmeSessionStateName, false))
{
var readme = SelectReadme();
SessionState.SetBool(s_ShowedReadmeSessionStateName, true);
if (readme && !readme.loadedLayout)
{
LoadLayout();
readme.loadedLayout = true;
}
}
}
static void LoadLayout()
{
var assembly = typeof(EditorApplication).Assembly;
var windowLayoutType = assembly.GetType("UnityEditor.WindowLayout", true);
var method = windowLayoutType.GetMethod("LoadWindowLayout", BindingFlags.Public | BindingFlags.Static);
method.Invoke(null, new object[] { Path.Combine("TutorialInfo/Layout.wlt"), false });
}
static Readme SelectReadme()
{
var ids = AssetDatabase.FindAssets("Readme t:Readme");
if (ids.Length == 1)
{
var readmeObject = AssetDatabase.LoadMainAssetAtPath(AssetDatabase.GUIDToAssetPath(ids[0]));
Selection.objects = new UnityEngine.Object[] { readmeObject };
return (Readme)readmeObject;
}
else
{
Debug.Log("Couldn't find a readme");
return null;
}
}
protected override void OnHeaderGUI()
{
var readme = (Readme)target;
Init();
var iconWidth = Mathf.Min(EditorGUIUtility.currentViewWidth / 3f - 20f, 128f);
GUILayout.BeginHorizontal("In BigTitle");
{
if (readme.icon != null)
{
GUILayout.Space(k_Space);
GUILayout.Label(readme.icon, GUILayout.Width(iconWidth), GUILayout.Height(iconWidth));
}
GUILayout.Space(k_Space);
GUILayout.BeginVertical();
{
GUILayout.FlexibleSpace();
GUILayout.Label(readme.title, TitleStyle);
GUILayout.FlexibleSpace();
}
GUILayout.EndVertical();
GUILayout.FlexibleSpace();
}
GUILayout.EndHorizontal();
}
public override void OnInspectorGUI()
{
var readme = (Readme)target;
Init();
foreach (var section in readme.sections)
{
if (!string.IsNullOrEmpty(section.heading))
{
GUILayout.Label(section.heading, HeadingStyle);
}
if (!string.IsNullOrEmpty(section.text))
{
GUILayout.Label(section.text, BodyStyle);
}
if (!string.IsNullOrEmpty(section.linkText))
{
if (LinkLabel(new GUIContent(section.linkText)))
{
Application.OpenURL(section.url);
}
}
GUILayout.Space(k_Space);
}
if (GUILayout.Button("Remove Readme Assets", ButtonStyle))
{
RemoveTutorial();
}
}
bool m_Initialized;
GUIStyle LinkStyle
{
get { return m_LinkStyle; }
}
[SerializeField]
GUIStyle m_LinkStyle;
GUIStyle TitleStyle
{
get { return m_TitleStyle; }
}
[SerializeField]
GUIStyle m_TitleStyle;
GUIStyle HeadingStyle
{
get { return m_HeadingStyle; }
}
[SerializeField]
GUIStyle m_HeadingStyle;
GUIStyle BodyStyle
{
get { return m_BodyStyle; }
}
[SerializeField]
GUIStyle m_BodyStyle;
GUIStyle ButtonStyle
{
get { return m_ButtonStyle; }
}
[SerializeField]
GUIStyle m_ButtonStyle;
void Init()
{
if (m_Initialized)
return;
m_BodyStyle = new GUIStyle(EditorStyles.label);
m_BodyStyle.wordWrap = true;
m_BodyStyle.fontSize = 14;
m_BodyStyle.richText = true;
m_TitleStyle = new GUIStyle(m_BodyStyle);
m_TitleStyle.fontSize = 26;
m_HeadingStyle = new GUIStyle(m_BodyStyle);
m_HeadingStyle.fontStyle = FontStyle.Bold;
m_HeadingStyle.fontSize = 18;
m_LinkStyle = new GUIStyle(m_BodyStyle);
m_LinkStyle.wordWrap = false;
// Match selection color which works nicely for both light and dark skins
m_LinkStyle.normal.textColor = new Color(0x00 / 255f, 0x78 / 255f, 0xDA / 255f, 1f);
m_LinkStyle.stretchWidth = false;
m_ButtonStyle = new GUIStyle(EditorStyles.miniButton);
m_ButtonStyle.fontStyle = FontStyle.Bold;
m_Initialized = true;
}
bool LinkLabel(GUIContent label, params GUILayoutOption[] options)
{
var position = GUILayoutUtility.GetRect(label, LinkStyle, options);
Handles.BeginGUI();
Handles.color = LinkStyle.normal.textColor;
Handles.DrawLine(new Vector3(position.xMin, position.yMax), new Vector3(position.xMax, position.yMax));
Handles.color = Color.white;
Handles.EndGUI();
EditorGUIUtility.AddCursorRect(position, MouseCursor.Link);
return GUI.Button(position, label, LinkStyle);
}
}

Unity Facebook SDK build malfunctioning - Unity 5.1, FB SDK 6.2.2

I'm having some trouble with a Facebook Login/Share POC I've put together for the Unity Web Player. When I run it in the editor everything runs fine. I can login, retrieve profile name and picture and share to wall. When I create a build for Web Player however, nothing functions. Clicking login does nothing and all UI elements show up at start even though in code I've set many to be inactive until the login button is clicked. Would really appreciate some help on this, I have no idea why it's getting built incorrectly. Has anyone else experienced this?
Link: https://locomoku.com/projects/facebook/
public GameObject UIFBIsLoggedIn;
public GameObject UIFBNotLoggedIn;
public GameObject UIFBAvatar;
public GameObject UIFBUserName;
private Dictionary<string, string> profile = null;
void Awake()
{
FB.Init(SetInit, OnHideUnity);
}
private void SetInit()
{
Debug.Log("FB Init Done");
if(FB.IsLoggedIn)
{
Debug.Log("FB Logged in");
DealWithFBMenus(true);
}
else
{
DealWithFBMenus(false);
}
}
private void OnHideUnity(bool isGameShown)
{
if(!isGameShown)
{
Time.timeScale = 0;
}
else
{
Time.timeScale = 1;
}
}
public void FBLogin()
{
FB.Login("public_profile, user_friends", AuthCallback);
}
void AuthCallback(FBResult result)
{
if(FB.IsLoggedIn)
{
Debug.Log("FB Login Worked");
DealWithFBMenus(true);
}
else
{
Debug.Log("FB Login Fail");
DealWithFBMenus(false);
}
}
void DealWithFBMenus(bool isLoggedIn)
{
if(isLoggedIn)
{
UIFBIsLoggedIn.SetActive(true);
UIFBNotLoggedIn.SetActive(false);
// Get Profile Picture Code
FB.API(Util.GetPictureURL("me",128,128),Facebook.HttpMethod.GET,DealWithProfilePicture);
// Get User Name Code
FB.API("/me?fields=id,first_name", Facebook.HttpMethod.GET, DealWithUserName);
}
else
{
UIFBIsLoggedIn.SetActive(false);
UIFBNotLoggedIn.SetActive(true);
}
}
void DealWithProfilePicture(FBResult result)
{
if (result.Error == null)
{
Image img = UIFBAvatar.GetComponent<Image>();
img.sprite = Sprite.Create(result.Texture, new Rect(0,0, 128, 128), new Vector2());
}
else{
Debug.Log("Error with Profile Picture");
}
}
void DealWithUserName(FBResult result)
{
if (result.Error == null)
{
profile = Util.DeserializeJSONProfile(result.Text);
Text userMsg = UIFBUserName.GetComponent<Text>();
userMsg.text = "Hello, " + profile["first_name"];
}
else{
Debug.Log("Error with Profile Name");
}
}
public void ShareWithFriends()
{
FB.Feed(
linkCaption: "Test Captions",
picture: "https://locomoku.com/projects/facebook/shot.jpg",
linkName: "Test Link Name",
link: "http://locomoku.com"
);
}
The Util.cs code -
public static string GetPictureURL(string facebookID, int? width = null, int? height = null, string type = null)
{
string url = string.Format("/{0}/picture", facebookID);
string query = width != null ? "&width=" + width.ToString() : "";
query += height != null ? "&height=" + height.ToString() : "";
query += type != null ? "&type=" + type : "";
if (query != "") url += ("?g" + query);
return url;
}
public static void FriendPictureCallback(FBResult result)
{
if (result.Error != null)
{
Debug.LogError(result.Error);
return;
}
//GameStateManager.FriendTexture = result.Texture;
}
public static Dictionary<string, string> RandomFriend(List<object> friends)
{
var fd = ((Dictionary<string, object>)(friends[Random.Range(0, friends.Count - 1)]));
var friend = new Dictionary<string, string>();
friend["id"] = (string)fd["id"];
friend["first_name"] = (string)fd["first_name"];
return friend;
}
public static Dictionary<string, string> DeserializeJSONProfile(string response)
{
var responseObject = Json.Deserialize(response) as Dictionary<string, object>;
object nameH;
var profile = new Dictionary<string, string>();
if (responseObject.TryGetValue("first_name", out nameH))
{
profile["first_name"] = (string)nameH;
}
return profile;
}
public static List<object> DeserializeScores(string response)
{
var responseObject = Json.Deserialize(response) as Dictionary<string, object>;
object scoresh;
var scores = new List<object>();
if (responseObject.TryGetValue ("data", out scoresh))
{
scores = (List<object>) scoresh;
}
return scores;
}
public static List<object> DeserializeJSONFriends(string response)
{
var responseObject = Json.Deserialize(response) as Dictionary<string, object>;
object friendsH;
var friends = new List<object>();
if (responseObject.TryGetValue("friends", out friendsH))
{
friends = (List<object>)(((Dictionary<string, object>)friendsH)["data"]);
}
return friends;
}
public static void DrawActualSizeTexture (Vector2 pos, Texture texture, float scale = 1.0f)
{
Rect rect = new Rect (pos.x, pos.y, texture.width * scale , texture.height * scale);
GUI.DrawTexture(rect, texture);
}
public static void DrawSimpleText (Vector2 pos, GUIStyle style, string text)
{
Rect rect = new Rect (pos.x, pos.y, Screen.width, Screen.height);
GUI.Label (rect, text, style);
}

Set default value for string prompt

The editor class has a method called GetString which prompts the user for a string value via AutoCAD's command prompt. I call it in this wrapper method:
public static string PromptUserForString(string message = "Enter a string: ", string defaultAnswer = "")
{
return _editor.GetString("\n" + message).StringResult;
}
The argument message becomes the message the user sees when prompted for a string. How do I set it up so that the value of default answer is automatically set to be the answer so that if the user hits enter right away that becomes the value like in the screen shot below
So 1 is automatically typed as an answer meaning the user can either hit enter for the value of 1 or change 1 to whatever non-default answer they want
I paste you some code as example for the different prompts :
using System;
using System.Collections.Generic;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.ApplicationServices;
namespace EditorUtilities
{
/// <summary>
/// Prompts with the active document ( MdiActiveDocument )
/// </summary>
public class EditorHelper : IEditorHelper
{
private readonly Editor _editor;
public EditorHelper(Document document)
{
_editor = document.Editor;
}
public PromptEntityResult PromptForObject(string promptMessage, Type allowedType, bool exactMatchOfAllowedType)
{
var polyOptions = new PromptEntityOptions(promptMessage);
polyOptions.SetRejectMessage("Entity is not of type " + allowedType);
polyOptions.AddAllowedClass(allowedType, exactMatchOfAllowedType);
var polyResult = _editor.GetEntity(polyOptions);
return polyResult;
}
public PromptPointResult PromptForPoint(string promptMessage, bool useDashedLine = false, bool useBasePoint = false, Point3d basePoint = new Point3d(),bool allowNone = true)
{
var pointOptions = new PromptPointOptions(promptMessage);
if (useBasePoint)
{
pointOptions.UseBasePoint = true;
pointOptions.BasePoint = basePoint;
pointOptions.AllowNone = allowNone;
}
if (useDashedLine)
{
pointOptions.UseDashedLine = true;
}
var pointResult = _editor.GetPoint(pointOptions);
return pointResult;
}
public PromptPointResult PromptForPoint(PromptPointOptions promptPointOptions)
{
return _editor.GetPoint(promptPointOptions);
}
public PromptDoubleResult PromptForDouble(string promptMessage, double defaultValue = 0.0)
{
var doubleOptions = new PromptDoubleOptions(promptMessage);
if (Math.Abs(defaultValue - 0.0) > Double.Epsilon)
{
doubleOptions.UseDefaultValue = true;
doubleOptions.DefaultValue = defaultValue;
}
var promptDoubleResult = _editor.GetDouble(doubleOptions);
return promptDoubleResult;
}
public PromptIntegerResult PromptForInteger(string promptMessage)
{
var promptIntResult = _editor.GetInteger(promptMessage);
return promptIntResult;
}
public PromptResult PromptForKeywordSelection(
string promptMessage, IEnumerable<string> keywords, bool allowNone, string defaultKeyword = "")
{
var promptKeywordOptions = new PromptKeywordOptions(promptMessage) { AllowNone = allowNone };
foreach (var keyword in keywords)
{
promptKeywordOptions.Keywords.Add(keyword);
}
if (defaultKeyword != "")
{
promptKeywordOptions.Keywords.Default = defaultKeyword;
}
var keywordResult = _editor.GetKeywords(promptKeywordOptions);
return keywordResult;
}
public Point3dCollection PromptForRectangle(out PromptStatus status, string promptMessage)
{
var resultRectanglePointCollection = new Point3dCollection();
var viewCornerPointResult = PromptForPoint(promptMessage);
var pointPromptStatus = viewCornerPointResult.Status;
if (viewCornerPointResult.Status == PromptStatus.OK)
{
var rectangleJig = new RectangleJig(viewCornerPointResult.Value);
var jigResult = _editor.Drag(rectangleJig);
if (jigResult.Status == PromptStatus.OK)
{
// remove duplicate point at the end of the rectangle
var polyline = rectangleJig.Polyline;
var viewPolylinePoints = GeometryUtility.GetPointsFromPolyline(polyline);
if (viewPolylinePoints.Count == 5)
{
viewPolylinePoints.RemoveAt(4); // dont know why but true, probably mirror point with the last point
}
}
pointPromptStatus = jigResult.Status;
}
status = pointPromptStatus;
return resultRectanglePointCollection;
}
public PromptSelectionResult PromptForSelection(string promptMessage = null, SelectionFilter filter = null)
{
var selectionOptions = new PromptSelectionOptions { MessageForAdding = promptMessage };
var selectionResult = String.IsNullOrEmpty(promptMessage) ? _editor.SelectAll(filter) : _editor.GetSelection(selectionOptions, filter);
return selectionResult;
}
public PromptSelectionResult PromptForSelection(PromptSelectionOptions promptSelectionOptions,SelectionFilter filter = null)
{
return _editor.GetSelection(promptSelectionOptions, filter);
}
public void WriteMessage(string message)
{
_editor.WriteMessage(message);
}
public void DrawVector(Point3d from, Point3d to, int color, bool drawHighlighted)
{
_editor.DrawVector(from, to, color, drawHighlighted);
}
}
}

SharpDXException on setting Shader inputLayout

This didnt used to throw this exception but now it does
if (shader.ShaderInput == null) shader.ShaderInput = new InputLayout(OneEngineInstance.EngineInstance.Device, ShaderSignature.GetInputSignature(shader.CompilationResult), new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32_Float, 16, 0) });
The only useful information it gives me is
An unhandled exception of type 'SharpDX.SharpDXException' occurred in SharpDX.dll
Additional information: HRESULT: [0x80070057], Module: [General], ApiCode: [E_INVALIDARG/Invalid Arguments], Message: The parameter is incorrect.
Im not sure why this is doing this and im still pretty new to SharpDX
AssetsLoader.cs
using System;
using System.IO;
using SharpDX;
using SharpDX.DXGI;
using SharpDX.Direct3D;
using SharpDX.Direct3D11;
using SharpDX.D3DCompiler;
using SharpDX.XAudio2;
using SharpDX.Multimedia;
using OneEngine.DataTypes;
using OneEngine.Core;
namespace OneEngine.Assets
{
public static class AssetsLoader
{
public static void LoadImage(Image image)
{
image.Texture = Texture2D.FromFile<Texture2D>(OneEngineInstance.EngineInstance.Device, image.FilePath);
image.ShaderResourceView = new ShaderResourceView(OneEngineInstance.EngineInstance.Device, image.Texture);
image.Sampler = new SamplerState(OneEngineInstance.EngineInstance.Device, new SamplerStateDescription()
{
// TODO > Make Simplifier classes for these values and adapt to engine settings
Filter = Filter.MinMagMipLinear,
AddressU = TextureAddressMode.Wrap,
AddressV = TextureAddressMode.Wrap,
AddressW = TextureAddressMode.Wrap,
BorderColor = Color.Black,
ComparisonFunction = Comparison.Never,
MaximumAnisotropy = 16,
MipLodBias = 0,
MinimumLod = 0,
MaximumLod = 16
});
}
public static void LoadShader(Shader shader)
{
for (int i = 0; i < shader.ShaderTypes.Length; i++)
{
switch (shader.ShaderTypes[i])
{
case EShaderType.VERTEX:
shader.CompilationResult = ShaderBytecode.CompileFromFile(shader.FilePath, "VS", "vs_5_0");
shader.VertexShader = new VertexShader(OneEngineInstance.EngineInstance.Device, shader.CompilationResult);
break;
case EShaderType.PIXEL:
shader.CompilationResult = ShaderBytecode.CompileFromFile(shader.FilePath, "PS", "ps_5_0");
shader.PixelShader = new PixelShader(OneEngineInstance.EngineInstance.Device, shader.CompilationResult);
break;
case EShaderType.GEOMETRY:
shader.CompilationResult = ShaderBytecode.CompileFromFile(shader.FilePath, "GS", "gs_5_0");
shader.GeometryShader = new GeometryShader(OneEngineInstance.EngineInstance.Device, shader.CompilationResult);
break;
case EShaderType.COMPUTE:
shader.CompilationResult = ShaderBytecode.CompileFromFile(shader.FilePath, "CS", "cs_5_0");
shader.ComputeShader = new ComputeShader(OneEngineInstance.EngineInstance.Device, shader.CompilationResult);
break;
case EShaderType.DOMAIN:
shader.CompilationResult = ShaderBytecode.CompileFromFile(shader.FilePath, "DS", "ds_5_0");
shader.DomainShader = new DomainShader(OneEngineInstance.EngineInstance.Device, shader.CompilationResult);
break;
case EShaderType.HULL:
shader.CompilationResult = ShaderBytecode.CompileFromFile(shader.FilePath, "HS", "hs_5_0");
shader.HullShader = new HullShader(OneEngineInstance.EngineInstance.Device, shader.CompilationResult);
break;
}
}
if (shader.ShaderInput == null) shader.ShaderInput = new InputLayout(OneEngineInstance.EngineInstance.Device, ShaderSignature.GetInputSignature(shader.CompilationResult), new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32_Float, 16, 0) });
}
public static void LoadAudio(Audio audio)
{
audio.Stream = new SoundStream(File.OpenRead(audio.FilePath));
audio.Format = audio.Stream.Format;
audio.Buffer = new AudioBuffer
{
Stream = audio.Stream.ToDataStream(), AudioBytes = (int)audio.Stream.Length, Flags = BufferFlags.EndOfStream
};
audio.Stream.Close();
audio.Voice = new SourceVoice(AudioCore.XAudio, audio.Format, true);
if (audio.IsLoopable) audio.Buffer.LoopCount = audio.LoopTimes;
}
public static void LoadVideo()
{
}
public static void LoadFont()
{
}
public static void LoadLanguage()
{
}
}
public enum EShaderType
{
VERTEX, PIXEL, GEOMETRY, COMPUTE, DOMAIN, HULL
}
}
Shader.cs
using System;
using SharpDX.Direct3D;
using SharpDX.Direct3D11;
using SharpDX.D3DCompiler;
using OneEngine.Assets;
namespace OneEngine.DataTypes
{
public sealed class Shader
{
private String filePath;
private EShaderType[] shaderTypes;
private CompilationResult shaderByteCode;
private VertexShader vs;
private PixelShader ps;
private GeometryShader gs;
private ComputeShader cs;
private DomainShader ds;
private HullShader hs;
private InputLayout shaderInput;
private InputElement[] inputElements;
public Shader(String shaderFilePath, EShaderType[] types, InputElement[] elemets)
{
this.filePath = shaderFilePath;
this.shaderTypes = types;
this.inputElements = elemets;
}
public void RemoveFromMemory()
{
if (shaderByteCode != null) shaderByteCode.Dispose();
if (vs != null) vs.Dispose();
if (ps != null) ps.Dispose();
if (gs != null) gs.Dispose();
if (cs != null) cs.Dispose();
if (ds != null) ds.Dispose();
if (hs != null) hs.Dispose();
}
public String FilePath
{
get { return filePath; }
}
public EShaderType[] ShaderTypes
{
get { return shaderTypes; }
set { shaderTypes = value; }
}
public CompilationResult CompilationResult
{
get { return shaderByteCode; }
set { shaderByteCode = value; }
}
public VertexShader VertexShader
{
get { return vs; }
set { vs = value; }
}
public PixelShader PixelShader
{
get { return ps; }
set { ps = value; }
}
public GeometryShader GeometryShader
{
get { return gs; }
set { gs = value; }
}
public ComputeShader ComputeShader
{
get { return cs; }
set { cs = value; }
}
public DomainShader DomainShader
{
get { return ds; }
set { ds = value; }
}
public HullShader HullShader
{
get { return hs; }
set { hs = value; }
}
public InputLayout ShaderInput
{
set { shaderInput = value; }
get { return shaderInput; }
}
public InputElement[] ShaderInputElements
{
get { return inputElements; }
}
}
}
If you need anything else, the project is open source https://github.com/TheNanonNetwork/OneGames
Try creating your Graphics Device with DeviceCreationFlags.Debug and if the input layout is failing to create properly, then it'll tell you why.
Also, are you sure your Color attribute is supposed to be at an offset of 16 bytes given that the attribute before it is only 12 bytes in size?

how to pass json with wwwform in unity

I am a newbie in unity.
i want to send a post request having following json data in unity
**url** = "http://index.php"
**sampple json** = {"id":"100","name":"abc"}
I am using C#
can anyone provide me a solution for this?
I've done for doing this below. Let's go : ==>
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class btnGetData : MonoBehaviour {
void Start()
{
gameObject.GetComponent<Button>().onClick.AddListener(TaskOnClick);
}
IEnumerator WaitForWWW(WWW www)
{
yield return www;
string txt = "";
if (string.IsNullOrEmpty(www.error))
txt = www.text; //text of success
else
txt = www.error; //error
GameObject.Find("Txtdemo").GetComponent<Text>().text = "++++++\n\n" + txt;
}
void TaskOnClick()
{
try
{
GameObject.Find("Txtdemo").GetComponent<Text>().text = "starting..";
string ourPostData = "{\"plan\":\"TESTA02\"";
Dictionary<string,string> headers = new Dictionary<string, string>();
headers.Add("Content-Type", "application/json");
//byte[] b = System.Text.Encoding.UTF8.GetBytes();
byte[] pData = System.Text.Encoding.ASCII.GetBytes(ourPostData.ToCharArray());
///POST by IIS hosting...
WWW api = new WWW("http://192.168.1.120/si_aoi/api/total", pData, headers);
///GET by IIS hosting...
///WWW api = new WWW("http://192.168.1.120/si_aoi/api/total?dynamix={\"plan\":\"TESTA02\"");
StartCoroutine(WaitForWWW(api));
}
catch (UnityException ex) { Debug.Log(ex.Message); }
}
}
Well i've working with something like this:
public class RequestConnectionManager : Manager<RequestConnectionManager>
{
public int maxSubmissionAttempts = 3;
public Coroutine post() {
WWWForm playForm = new WWWForm();
playForm.AddField("id", myJson.id);
playForm.AddField("name", myJson.name);
Post playPost = new Post("http://index.php", playForm, maxSubmissionAttempts, this);
return StartCoroutine(PostWorker(playPost));
}
private IEnumerator PostWorker(Post playPost)
{
yield return null;
yield return playPost.Submit();
Debug.Log(playPost.Response);
if (playPost.Error != null)
{
MessageBoxManager.Instance.Show("Error: " + playPost.Error, "Error", MessageBoxManager.OKCancelOptionLabels, MessageOptions.Ok);
}
else
{
try
{
//do whatever you want in here
//Hashtable response = JsonReader.Deserialize<Hashtable>(playPost.Response);
//Debug.Log("UNITY LOG..." + response);
}
catch (JsonDeserializationException jsExc)
{
Debug.Log(jsExc.Message);
Debug.Log(playPost.Response);
}
catch (Exception exc)
{
Debug.Log(exc.Message);
Debug.Log(playPost.Response);
}
}
}
}
//As for the Manager class...
using UnityEngine;
using System.Collections;
// I wonder what the constraint where TManager : Singleton<TManager> would produce...
public class Manager<TManager> : SingletonW<TManager> where TManager : MonoBehaviour
{
override protected void Awake()
{
base.Awake();
DontDestroyOnLoad(this);
DontDestroyOnLoad(gameObject);
}
}
Hope this helps! =)

Categories